<?php

/*
  +--------------------------------------------------------------------------
  |   Invision Power Board
  |   =============================================
  |   by Matthew Mecham
  |   (c) 2001 - 2006 Invision Power Services, Inc.
  |
  |   =============================================
  |
  |
  +---------------------------------------------------------------------------
  |   > $Date: 2007-05-02 17:29:12 -0400 (Wed, 02 May 2007) $
  |   > $Revision: 959 $
  |   > $Author: BabyWolf $
  +---------------------------------------------------------------------------
  |
  |   > Access the dkm_bank files
  |   > Module written by BabyWolf
  |   > Date started: 07th February 2009
  |
  |	> Module Version Number: 1.0.0
  |   > DBA Checked: Sat 07 Feb 2009
  |   > Quality Checked: Sat 07 Feb. 2009
  +--------------------------------------------------------------------------
 */


if (!defined('IN_IPB')) {
    print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded all the relevant files.";
    exit();
}

class dkm_regportal {
    # Classes

    var $ipsclass;
    var $common;
    # Others
    var $custom_fields;
    var $output = "";
    var $page_title = "";
    var $nav = array();
    var $html = "";
    var $random_flash = "";
    /* ------------------------------------------------------------------------- */

    //  Begin Auto run function
    /* ------------------------------------------------------------------------- */
    function auto_run() {
        //-----------------------------------------
        // Require the HTML and language modules
        $this->init();
        $this->base_url = "{$this->ipsclass->vars['profile_url']}/{$this->ipsclass->member['name']}/{$this->ipsclass->lang['seoPanelPage']}{$this->ipsclass->lang['seoPageSuffix']}";
        //$this->base_url = $this->ipsclass->base_url . "act=regportal";
        $this->base_url_nosess = "{$this->ipsclass->vars['board_url']}/index.{$this->ipsclass->vars['php_ext']}";
        
        //$this->page_title = $this->ipsclass->lang['home_title'];
                
        //-----------------------------------------
        // Get the emailer module
        //-----------------------------------------
        
        //echo ($this->ipsclass->member['dkm_HP']);exit();
        require_once( ROOT_PATH . 'sources/action_public/Common.php' );
        $this->common = new Common();
        $this->common->ipsclass = & $this->ipsclass;
        if (!$this->ipsclass->member['id']) {
            $this->ipsclass->input['last_visit'] = time();
        }
        if ($this->ipsclass->vars['ipbli_usertype'] != 'username') {
            $this->ipsclass->lang['qli_name'] = $this->ipsclass->lang['email_address'];
        }
        $this->ipsclass->member['last_visit'] = $this->ipsclass->get_date($this->ipsclass->member['last_visit'], 'SHORT');
        if($this->ipsclass->member['bday_year']!="0")
        {
            $this->ipsclass->yearold=date("Y",time())- $this->ipsclass->member['bday_year'];
        }
        else
        {
            $this->ipsclass->yearold="Chưa rỏ";
        }
        $this->output .= $this->ipsclass->compiled_templates['skin_global']->global_board_header($this->ipsclass->get_date($this->ipsclass->input['last_visit'], 'LONG'));
        
        require ROOT_PATH . "sources/classes/class_email.php";

        $this->email = new emailer();
        $this->email->ipsclass = & $this->ipsclass;
        $this->email->email_init();

        if (USE_MODULES == 1) {
            require ROOT_PATH . "modules/ipb_member_sync.php";

            $this->modules = new ipb_member_sync();
            $this->modules->ipsclass = & $this->ipsclass;
        }
//        if($this->ipsclass->input['CODE'] == ""){
//            $this->ipsclass->input['CODE'] == "wg";
//        }
        //-----------------------------------------
        // What to do?
        //-----------------------------------------
        //echo $this->ipsclass->input['CODE'];exit();
        switch ($this->ipsclass->input['CODE']) {
            case 'process': // Create account
                $this->regportal_process();
                break;
            case 'termsread':// Read Terms
                $this->show_terms_read();
                break;
            case 'quickregister':
                $this->show_terms_read("", 1);
                break;
            case 'result':
                $this->show_search_result();
                break;
            case 'import_members':
                $this->import_members();
                break;
            case 'fix_member_data':
                $this->fix_member_data();
                break;
            case 'wg':
                $this->ipsclass->pageTitle = $this->ipsclass->lang['home_title'];
                $this->my_show_page_cpanel();
                break;
            case 'pf':
                $this->ipsclass->pageTitle = $this->ipsclass->lang['profile_title'];
                $this->my_show_page_profile();
                break;
            case 'sr':
                $this->my_show_page_search();
                break;
            case 'edit-pro-info':
                $this->my_ajax_edit_profile();
                //exit();
                break;
            case 'change-pass':
                $this->change_password();
                break;
            case 'change-pic':
                //$this->change_pic();
                $this->do_avatar();
                break;
            case 'delete-pic':
                $this->delete_pic();
                break;
            case 'own-comment':
                $this->owned_comment();
                break;
            case 'comment-paging':
                $this->load_comments();
                break;
            case "delete-own-comment":
                $this->delete_owned_comment();
                break;
            case "search-friends":
                $this->ipsclass->pageTitle = $this->ipsclass->lang['Danh sach ban be'];
                $this->find_friends_by_name();
                break;
            case "suggest-search-friends":
                $this->search_suggest();
                break;
            case "load-all-member":
                $this->load_all_member();
                break;
            case "own-add-friend":
                $this->add_friend();
                break;
            case "is-friend":
                $this->is_friend();
                break;
            case "member-view-friend-profile":
                $this->member_view_friend_profile();
                break;
            case "member-approve-friends":
                $this->member_approve_friends();
                break;
            case "approve-friend":
                $this->approve_friend();
                break;
            case "reject-friend":
                $this->reject_friend();
                break;
            case "remove-friend":
                $this->remove_friend();
                break;
            case "member-logout":
                $this->logout();
                break;
            case "load-all-friends":
                $this->load_all_friends();
                $this->page_title = $this->ipsclass->lang['profile_title'];
                $this->nav = array($this->ipsclass->lang['profile_title']);
                break;
            case "redirect":
                $this->redirect();
                break;

            default:
                $this->my_show_page();
                break;
            
        }
        //$this->common->load_friends();
        //var_dump($this->ipsclass->member);exit();
        //-----------------------------------------
        // If we have any HTML to print, do so...
        //-----------------------------------------
        require_once( ROOT_PATH . 'sources/action_public/Common.php' );
        $common = new Common();
        $common->ipsclass = & $this->ipsclass;
        $this->output .=  $common->load_right_content();
        //echo $common->load_avatar_info_content();
        
        $this->ipsclass->print->add_output("$this->output");
        $this->ipsclass->print->do_output(array('TITLE' => $this->page_title, 'JS' => 0, 'NAV' => $this->nav));
    }

    //-----------------------------------------
    // Created by tuanhnm on 22/07/2011
    //-----------------------------------------    	
    function my_show_page($form_errors=array()) {
        //echo "asasa";exit();
        if(intval($this->ipsclass->member['id']) >0){
            //$this->ipsclass->boink_it($this->ipsclass->base_url . '&act=regportal&CODE=wg');
            $this->ipsclass->boink_it("{$this->ipsclass->vars['profile_url']}/{$this->ipsclass->member['name']}/{$this->ipsclass->lang['seoPanelPage']}{$this->ipsclass->lang['seoPageSuffix']}");
            exit();
        }
        //$this->page_title = $this->ipsclass->lang['games_title'];
        //$this->nav = array($this->ipsclass->lang['games_title']);
        $this->ipsclass->load_template('skin_intro');
        $this->output = $this->ipsclass->compiled_templates['skin_intro']->main_page();
        print $this->output;
        exit();
    }
 
    //-------------------------------------------
    // Begin show_terms_read
    //-------------------------------------------
    function show_terms_read($reg_code_err_msg="", $short_register=0) {

        //-----------------------------------------
        // INIT
        //-----------------------------------------
        $this->page_title = $this->ipsclass->lang['register_title'];
        $this->nav = array($this->ipsclass->lang['register_title']);
        if ($reg_code_err_msg) {
            $this->ipsclass->input = array_merge($this->ipsclass->input, $_SESSION);
            $_POST['act'] = 'termsread';
            $_POST = array_merge($_POST, $_SESSION);
        }

        if ($this->ipsclass->vars['ipbli_usertype'] == 'email') {
            $this->ipsclass->input['UserName'] = $this->ipsclass->input['members_display_name'];
        }

        $form_errors = array();
        $coppa = ($this->ipsclass->input['coppa_user'] == 1) ? 1 : 0;
        $in_username = str_replace('|', '&#124;', $this->ipsclass->input['UserName']);
        $in_password = trim($this->ipsclass->input['PassWord']);
        $in_email = strtolower(trim($this->ipsclass->input['EmailAddress']));
        $banfilters = array();
        $members_display_name = trim($this->ipsclass->input['members_display_name']);


        //-----------------------------------------
        // Load ban filters
        //-----------------------------------------

        $this->ipsclass->DB->simple_construct(array('select' => '*', 'from' => 'banfilters'));
        $this->ipsclass->DB->simple_exec();

        while ($r = $this->ipsclass->DB->fetch_row()) {
            $banfilters[$r['ban_type']][] = $r['ban_content'];
        }

        //-----------------------------------------
        // Check
        //-----------------------------------------

        if ($_POST['act'] == "") {
            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'complete_form'));
        }

        if ($this->ipsclass->vars['no_reg'] == 1) {
            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'reg_off'));
        }

        //-----------------------------------------
        // Custom profile field stuff
        //-----------------------------------------

        require_once( ROOT_PATH . 'sources/classes/class_custom_fields.php' );
        $fields = new custom_fields($this->ipsclass->DB);

        $fields->cache_data = $this->ipsclass->cache['profilefields'];

        $fields->init_data();
        $fields->parse_to_save(1);

        //-----------------------------------------
        // Check...
        //-----------------------------------------

        if (count($fields->error_fields['empty'])) {
            foreach ($fields->error_fields['empty'] as $cfield) {
                $form_errors['cfield_' . $cfield['pf_id']][$this->ipsclass->lang['err_complete_form']] = $this->ipsclass->lang['err_complete_form'];
            }
        }

        if (count($fields->error_fields['invalid'])) {
            foreach ($fields->error_fields['invalid'] as $cfield) {
                $form_errors['cfield_' . $cfield['pf_id']][$this->ipsclass->lang['err_invalid']] = $this->ipsclass->lang['err_invalid'];
            }
        }

        if (count($fields->error_fields['toobig'])) {
            foreach ($fields->error_fields['toobig'] as $cfield) {
                $form_errors['cfield_' . $cfield['pf_id']][$this->ipsclass->lang['err_cf_to_long']] = $this->ipsclass->lang['err_cf_to_long'];
            }
        }

        //-----------------------------------------
        // Remove multiple spaces in the username
        //-----------------------------------------

        $in_username = preg_replace("/\s{2,}/", " ", $in_username);

        //-----------------------------------------
        // Remove linebreaks if set to
        //-----------------------------------------

        if ($this->ipsclass->vars['usernames_nobr']) {
            $in_username = $this->ipsclass->my_br2nl($in_username);
            $in_username = str_replace("\n", "", $in_username);
            $in_username = str_replace("\r", "", $in_username);

            $members_display_name = $this->ipsclass->my_br2nl($members_display_name);
            $members_display_name = str_replace("\n", "", $members_display_name);
            $members_display_name = str_replace("\r", "", $members_display_name);
        }

        //-----------------------------------------
        // Remove 'sneaky' spaces
        //-----------------------------------------

        if ($this->ipsclass->vars['strip_space_chr']) {
            // use hexdec to convert between '0xAD' and chr
            $in_username = str_replace(chr(160), ' ', $in_username);
            $in_username = str_replace(chr(173), ' ', $in_username);
            $in_username = str_replace(chr(240), ' ', $in_username);
            $members_display_name = str_replace(chr(160), ' ', $members_display_name);
            $members_display_name = str_replace(chr(173), ' ', $members_display_name);
            $members_display_name = str_replace(chr(240), ' ', $members_display_name);
        }

        //-----------------------------------------
        // Trim up..
        //-----------------------------------------

        $in_username = trim($in_username);

        //-----------------------------------------
        // Test unicode name too
        //-----------------------------------------

        $unicode_name = preg_replace_callback('/&#([0-9]+);/si', create_function('$matches', 'return chr($matches[1]);'), $in_username);
        $unicode_name = str_replace("'", '&#39;', $unicode_name);
        $unicode_name = str_replace("\\", '&#92;', $unicode_name);

        $unicode_dname = preg_replace_callback('/&#([0-9]+);/si', create_function('$matches', 'return chr($matches[1]);'), $members_display_name);
        $unicode_dname = str_replace("'", '&#39;', $unicode_dname);
        $unicode_dname = str_replace("\\", '&#92;', $unicode_dname);

        //-----------------------------------------
        // Check the email address
        //-----------------------------------------

        $in_email = $this->ipsclass->clean_email($in_email);

        if (!$in_email OR strlen($in_email) < 6) {
            $form_errors['email'][$this->ipsclass->lang['err_invalid_email']] = $this->ipsclass->lang['err_invalid_email'];
            echo "&errorStatus=1";
            echo "&messageStatus=" . $this->ipsclass->lang['err_invalid_email'];
            exit();
        }

        //-----------------------------------------
        // Test email address
        //-----------------------------------------
        // ---------------------------------------
        // Updated by hnmtuan on 06/08/2011
        // ---------------------------------------
        $this->ipsclass->input['EmailAddress'] = strtolower(trim($this->ipsclass->input['EmailAddress']));
        $this->ipsclass->input['EmailAddress_two'] = $this->ipsclass->input['EmailAddress'];
        //$this->ipsclass->input['EmailAddress_two'] = strtolower( trim($this->ipsclass->input['EmailAddress_two']) );
        //$this->ipsclass->input['EmailAddress']     = strtolower( trim($this->ipsclass->input['EmailAddress']) );

        if (preg_match("#[\;\#\n\r\*\'\"<>&\%\!\(\)\{\}\[\]\?\\/\s]#", $this->ipsclass->input['EmailAddress_two'])) {
            $form_errors['email'][$this->ipsclass->lang['reg_error_email_invalid']] = $this->ipsclass->lang['reg_error_email_invalid'];
            echo "&errorStatus=1";
            echo "&messageStatus=" . $this->ipsclass->lang['reg_error_email_invalid'];
            exit();
        }
        //else {
        // ---------------------------------------
        // Updated by hnmtuan on 06/08/2011
        // ---------------------------------------
        /*
          if ( $in_email AND $this->ipsclass->input['EmailAddress_two'] != $in_email)
          {
          $form_errors['email'][$this->ipsclass->lang['reg_error_email_nm']] = $this->ipsclass->lang['reg_error_email_nm'];
          }
         * */
        // }
        //-----------------------------------------
        // More unicode..
        //-----------------------------------------

        $len_u = preg_replace("/&#([0-9]+);/", "-", $in_username);
        $len_p = preg_replace("/&#([0-9]+);/", "-", $in_password);
        $len_d = preg_replace("/&#([0-9]+);/", "-", $members_display_name);

        //-----------------------------------------
        // Test dname
        //-----------------------------------------

        if ($this->ipsclass->vars['auth_allow_dnames']) {
            if (!$members_display_name OR strlen($len_d) < 3 OR strlen($len_d) > $this->ipsclass->vars['max_user_name_length']) {
                $form_errors['dname'][$this->ipsclass->lang['reg_error_no_name']] = $this->ipsclass->lang['reg_error_no_name'];
                echo "&errorStatus=1";
                echo "&messageStatus=" . $this->ipsclass->lang['reg_error_no_name'];
                exit();
            }
        }

        $this->ipsclass->vars['username_characters'] = 0;
        if ($this->ipsclass->vars['username_characters']) {
            $check_against = preg_quote($this->ipsclass->vars['username_characters'], "/");

            if (!preg_match("/^[" . $check_against . "]+$/i", $_POST['UserName']) && $this->ipsclass->vars['ipbli_usertype'] == 'username') {
                $msg = str_replace('{chars}', $this->ipsclass->vars['username_characters'], $this->ipsclass->vars['username_errormsg']);
                $form_errors['username'][$msg] = $msg;
                echo "&errorStatus=1";
                echo "&messageStatus=" . $msg;
                exit();
            }

            if (!preg_match("/^[" . $check_against . "]+$/i", $_POST['members_display_name']) && $this->ipsclass->vars['auth_allow_dnames']) {
                $msg = str_replace('{chars}', $this->ipsclass->vars['username_characters'], $this->ipsclass->vars['username_errormsg']);
                $form_errors['dname'][$msg] = $msg;
                echo "&errorStatus=1";
                echo "&messageStatus=" . $msg;
                exit();
            }
        }

        //-----------------------------------------
        // Check for errors in the input.
        //-----------------------------------------

        if (!$in_username OR strlen($len_u) < 4 OR strlen($len_u) > $this->ipsclass->vars['max_user_name_length']) {
            $form_errors['username'][$this->ipsclass->lang['reg_error_username_none']] = $this->ipsclass->lang['reg_error_username_none'];
            echo "&errorStatus=1";
            echo "&messageStatus=" . $this->ipsclass->lang['reg_error_username_none'];
            exit();
        }

        if (!$in_password OR strlen($len_p) < 6 OR strlen($len_p) > $this->ipsclass->vars['max_user_name_length']) {
            $form_errors['password'][$this->ipsclass->lang['reg_error_no_pass']] = $this->ipsclass->lang['reg_error_no_pass'];
            echo "&errorStatus=1";
            echo "&messageStatus=" . $this->ipsclass->lang['reg_error_no_pass'];
            exit();
        }

        // ---------------------------------------
        // Updated by hnmtuan on 06/08/2011
        // ---------------------------------------
        //$this->ipsclass->input['PassWord_Check'] = $in_password;

        /*
          if ($this->ipsclass->input['PassWord_Check'] != $in_password)
          {
          $form_errors['password'][$this->ipsclass->lang['reg_error_pass_nm']] = $this->ipsclass->lang['reg_error_pass_nm'];
          }
         * */

        //-----------------------------------------
        // CHECK 1: Any errors (missing fields, etc)?
        //-----------------------------------------				

        if (count($form_errors)) {
            $this->show_page($form_errors);
            return;
        }


        //-----------------------------------------
        // USERNAME: Is this name already taken?
        //-----------------------------------------

        $this->ipsclass->DB->cache_add_query('login_getmember', array('username' => strtolower($in_username)));
        $this->ipsclass->DB->cache_exec_query();

        if ($name_check['id']) {
            $form_errors['username'][$this->ipsclass->lang['reg_error_username_taken']] = $this->ipsclass->lang['reg_error_username_taken'];
            echo "&errorStatus=1";
            echo "&messageStatus=" . $this->ipsclass->lang['reg_error_username_taken'];
            exit();
        }

        //-----------------------------------------
        // USERNAME: Is this name already taken (display)?
        //-----------------------------------------

        if ($this->ipsclass->vars['auth_allow_dnames']) {
            if ($this->ipsclass->vars['auth_dnames_nologinname']) {
                $this->ipsclass->DB->build_query(array('select' => "members_display_name, id",
                    'from' => 'members',
                    'where' => "members_l_display_name='" . strtolower($in_username) . "'",
                    'limit' => array(0, 1)));

                $this->ipsclass->DB->exec_query();

                if ($this->ipsclass->DB->get_num_rows()) {
                    $form_errors['username'][$this->ipsclass->lang['reg_error_username_taken']] = $this->ipsclass->lang['reg_error_username_taken'];
                    echo "&errorStatus=1";
                    echo "&messageStatus=" . $this->ipsclass->lang['reg_error_username_taken'];
                    exit();
                }
            }
        }

        //-----------------------------------------
        // USERNAME: Special chars?
        //-----------------------------------------

        if ($unicode_name != $in_username) {
            $this->ipsclass->DB->cache_add_query('login_getmember', array('username' => $this->ipsclass->DB->add_slashes(strtolower($unicode_name))));
            $this->ipsclass->DB->cache_exec_query();

            $name_check = $this->ipsclass->DB->fetch_row();

            if ($name_check['id']) {
                $form_errors['username'][$this->ipsclass->lang['reg_error_username_taken']] = $this->ipsclass->lang['reg_error_username_taken'];
                echo "&errorStatus=1";
                echo "&messageStatus=" . $this->ipsclass->lang['reg_error_username_taken'];
                exit();
            }
        }

        //-----------------------------------------
        // USERNAME: GUEST
        //-----------------------------------------

        if (strtolower($in_username) == 'guest') {
            $form_errors['username'][$this->ipsclass->lang['reg_error_username_taken']] = $this->ipsclass->lang['reg_error_username_taken'];
            echo "&errorStatus=1";
            echo "&messageStatus=" . $this->ipsclass->lang['reg_error_username_taken'];
            exit();
        }

        //-----------------------------------------
        // USERNAME: Banned?
        //-----------------------------------------

        if (is_array($banfilters['name']) and count($banfilters['name'])) {
            foreach ($banfilters['name'] as $n) {
                $n = str_replace('\*', '.*', preg_quote($n, "/"));

                if ($n AND preg_match("/^{$n}$/i", $in_username)) {
                    $form_errors['username'][$this->ipsclass->lang['reg_error_username_taken']] = $this->ipsclass->lang['reg_error_username_taken'];
                    echo "&errorStatus=1";
                    echo "&messageStatus=" . $this->ipsclass->lang['reg_error_username_taken'];
                    exit();
                }
            }
        }

        //-----------------------------------------
        // DNAME
        //-----------------------------------------

        if ($this->ipsclass->vars['auth_allow_dnames']) {
            //-----------------------------------------
            // Illegal characters
            //-----------------------------------------

            if (preg_match("#[\[\];,\|]#", str_replace('&#39;', "'", str_replace('&amp;', '&', $unicode_dname)))) {
                $form_errors['dname'][$this->ipsclass->lang['reg_error_chars']] = $this->ipsclass->lang['reg_error_chars'];
                echo "&errorStatus=1";
                echo "&messageStatus=" . $this->ipsclass->lang['reg_error_chars'];
                exit();
            }

            //-----------------------------------------
            // DNAME: Is this name already taken?
            //-----------------------------------------

            $this->ipsclass->DB->cache_add_query('general_get_by_display_name', array('members_display_name' => strtolower($members_display_name)));
            $this->ipsclass->DB->cache_exec_query();

            $name_check = $this->ipsclass->DB->fetch_row();

            if ($name_check['id']) {
                $form_errors['dname'][$this->ipsclass->lang['reg_error_taken']] = $this->ipsclass->lang['reg_error_taken'];
                echo "&errorStatus=1";
                echo "&messageStatus=" . $this->ipsclass->lang['reg_error_taken'];
                exit();
            }

            //-----------------------------------------
            // DNAME: Check for existing LOG IN name.
            //-----------------------------------------

            if ($this->ipsclass->vars['auth_dnames_nologinname']) {
                $this->ipsclass->DB->build_query(array('select' => "members_display_name, id",
                    'from' => 'members',
                    'where' => "members_l_username='" . strtolower($members_display_name) . "'",
                    'limit' => array(0, 1)));

                $this->ipsclass->DB->exec_query();

                if ($this->ipsclass->DB->get_num_rows()) {
                    $form_errors['dname'][$this->ipsclass->lang['reg_error_taken']] = $this->ipsclass->lang['reg_error_taken'];
                    echo "&errorStatus=1";
                    echo "&messageStatus=" . $this->ipsclass->lang['reg_error_taken'];
                    exit();
                }
            }

            //-----------------------------------------
            // DNAME: Special chars?
            //-----------------------------------------

            if ($unicode_dname != $members_display_name) {
                $this->ipsclass->DB->cache_add_query('general_get_by_display_name', array('members_display_name' => $this->ipsclass->DB->add_slashes(strtolower($unicode_dname))));
                $this->ipsclass->DB->cache_exec_query();

                $name_check = $this->ipsclass->DB->fetch_row();

                if ($name_check['id']) {
                    $form_errors['dname'][$this->ipsclass->lang['reg_error_taken']] = $this->ipsclass->lang['reg_error_taken'];
                    echo "&errorStatus=1";
                    echo "&messageStatus=" . $this->ipsclass->lang['reg_error_taken'];
                    exit();
                }
            }

            //-----------------------------------------
            // DNAME: Banned?
            //-----------------------------------------

            if (is_array($banfilters['name']) and count($banfilters['name'])) {
                foreach ($banfilters['name'] as $n) {
                    $n = str_replace('\*', '.*', preg_quote($n, "/"));

                    if ($n AND preg_match("/^{$n}$/i", $members_display_name)) {
                        $form_errors['dname'][$this->ipsclass->lang['reg_error_taken']] = $this->ipsclass->lang['reg_error_taken'];
                        echo "&errorStatus=1";
                        echo "&messageStatus=" . $this->ipsclass->lang['reg_error_taken'];
                        exit();
                    }
                }
            }

            //-----------------------------------------
            // DNAME: GUEST
            //-----------------------------------------

            if (strtolower($members_display_name) == 'guest') {
                $form_errors['dname'][$this->ipsclass->lang['reg_error_taken']] = $this->ipsclass->lang['reg_error_taken'];
                echo "&errorStatus=1";
                echo "&messageStatus=" . $this->ipsclass->lang['reg_error_taken'];
                exit();
            }
        }

        //-----------------------------------------
        // Is this email addy taken? CONVERGE THIS??
        //-----------------------------------------

        if ($this->ipsclass->converge->converge_check_for_member_by_email($in_email) == TRUE) {
            $form_errors['email'][$this->ipsclass->lang['reg_error_email_taken']] = $this->ipsclass->lang['reg_error_email_taken'];
            echo "&errorStatus=1";
            echo "&messageStatus=" . $this->ipsclass->lang['reg_error_email_taken'];
            exit();
        }

        //-----------------------------------------
        // Load handler...
        //-----------------------------------------

        require_once( ROOT_PATH . 'sources/handlers/han_login.php' );
        $this->han_login = new han_login();
        $this->han_login->ipsclass = & $this->ipsclass;
        $this->han_login->init();
        $this->han_login->email_exists_check($email);

        if ($this->han_login->return_code != 'METHOD_NOT_DEFINED' AND $this->han_login->return_code != 'EMAIL_NOT_IN_USE') {
            $form_errors['email'][$this->ipsclass->lang['reg_error_email_taken']] = $this->ipsclass->lang['reg_error_email_taken'];
            echo "&errorStatus=1";
            echo "&messageStatus=" . $this->ipsclass->lang['reg_error_email_taken'];
            exit();
        }

        //-----------------------------------------
        // Are they banned [EMAIL]?
        //-----------------------------------------

        if (is_array($banfilters['email']) and count($banfilters['email'])) {
            foreach ($banfilters['email'] as $email) {
                $email = str_replace('\*', '.*', preg_quote($email, "/"));

                if (preg_match("/^{$email}$/i", $in_email)) {
                    $form_errors['email'][$this->ipsclass->lang['reg_error_email_ban']] = $this->ipsclass->lang['reg_error_email_ban'];
                    echo "&errorStatus=1";
                    echo "&messageStatus=" . $this->ipsclass->lang['reg_error_email_ban'];
                    exit();
                }
            }
        }

        //print_r ($form_errors);
        //exit();		
        //-----------------------------------------
        // CHECK 2: Any errors (duplicate names, etc)?
        //-----------------------------------------


        if (count($form_errors)) {
            $this->show_page($form_errors);
            return;
        }


        //-----------------------------------------
        // INIT
        //-----------------------------------------

        $final_errors = array();

        if ($this->ipsclass->vars['no_reg'] == 1) {
            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'reg_off'));
        }

        $coppa = $this->ipsclass->my_getcookie('coppa');
        //$coppa = (isset($this->ipsclass->input['coppa_user']) AND $this->ipsclass->input['coppa_user'] == 1) ? 1 : 0;


        if ($coppa == 'yes') {
            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'awaiting_coppa'));
        }

        $this->ipsclass->vars['username_errormsg'] = str_replace('{chars}', $this->ipsclass->vars['username_characters'], $this->ipsclass->vars['username_errormsg']);


        if ($this->ipsclass->member['id']) {
            //-----------------------------------------
            // Log member out
            //-----------------------------------------

            require_once( ROOT_PATH . 'sources/action_public/login.php' );
            $login = new login();
            $login->ipsclass = & $this->ipsclass;
            $login->do_log_out(0);
        }

        //-----------------------------------------
        // Continue
        //-----------------------------------------
        $_SESSION = array_merge($_SESSION, array('coppa_user' => $this->ipsclass->input['coppa_user'],
            'UserName' => $this->ipsclass->input['UserName'],
            'members_display_name' => $this->ipsclass->input['members_display_name'],
            'day' => $this->ipsclass->input['day'],
            'month' => $this->ipsclass->input['month'],
            'year' => $this->ipsclass->input['year'],
            'EmailAddress' => $this->ipsclass->input['EmailAddress'],
            'EmailAddress_two' => $this->ipsclass->input['EmailAddress_two'],
            'PassWord' => $this->ipsclass->input['PassWord'],
            'PassWord_Check' => $this->ipsclass->input['PassWord_Check'],
            'country' => $this->ipsclass->input['country'],
            'city' => $this->ipsclass->input['city'],
            'district' => $this->ipsclass->input['district'],
            'ward' => $this->ipsclass->input['ward'],
            'address' => $this->ipsclass->input['address'],
            'siteLocation' => $this->ipsclass->input['siteLocation']
                )
        );


        //-----------------------------------------
        // Is this email addy taken? CONVERGE THIS??
        //-----------------------------------------

        if ($this->ipsclass->converge->converge_check_for_member_by_email($in_email) == TRUE) {
            $form_errors['email'][$this->ipsclass->lang['reg_error_email_taken']] = $this->ipsclass->lang['reg_error_email_taken'];
            echo "&errorStatus=1";
            echo "&messageStatus=" . $this->ipsclass->lang['reg_error_email_taken'];
            exit();
        }

        //-----------------------------------------
        // Load handler...
        //-----------------------------------------

        require_once( ROOT_PATH . 'sources/handlers/han_login.php' );
        $this->han_login = new han_login();
        $this->han_login->ipsclass = & $this->ipsclass;
        $this->han_login->init();
        $this->han_login->email_exists_check($email);

        if ($this->han_login->return_code != 'METHOD_NOT_DEFINED' AND $this->han_login->return_code != 'EMAIL_NOT_IN_USE') {
            $form_errors['email'][$this->ipsclass->lang['reg_error_email_taken']] = $this->ipsclass->lang['reg_error_email_taken'];
            echo "&errorStatus=1";
            echo "&messageStatus=" . $this->ipsclass->lang['reg_error_email_taken'];
            exit();
        }

        //-----------------------------------------
        // Are they banned [EMAIL]?
        //-----------------------------------------

        if (is_array($banfilters['email']) and count($banfilters['email'])) {
            foreach ($banfilters['email'] as $email) {
                $email = str_replace('\*', '.*', preg_quote($email, "/"));

                if (preg_match("/^{$email}$/i", $in_email)) {
                    $form_errors['email'][$this->ipsclass->lang['reg_error_email_ban']] = $this->ipsclass->lang['reg_error_email_ban'];
                    echo "&errorStatus=1";
                    echo "&messageStatus=" . $this->ipsclass->lang['reg_error_email_ban'];
                    exit();
                }
            }
        }

        //print_r ($form_errors);
        //exit();		
        //-----------------------------------------
        // CHECK 2: Any errors (duplicate names, etc)?
        //-----------------------------------------


        if (count($form_errors)) {
            $this->show_page($form_errors);
            return;
        }


        //-----------------------------------------
        // INIT
        //-----------------------------------------

        $final_errors = array();

        if ($this->ipsclass->vars['no_reg'] == 1) {
            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'reg_off'));
        }

        $coppa = $this->ipsclass->my_getcookie('coppa');
        //$coppa = (isset($this->ipsclass->input['coppa_user']) AND $this->ipsclass->input['coppa_user'] == 1) ? 1 : 0;


        if ($coppa == 'yes') {
            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'awaiting_coppa'));
        }

        $this->ipsclass->vars['username_errormsg'] = str_replace('{chars}', $this->ipsclass->vars['username_characters'], $this->ipsclass->vars['username_errormsg']);


        if ($this->ipsclass->member['id']) {
            //-----------------------------------------
            // Log member out
            //-----------------------------------------

            require_once( ROOT_PATH . 'sources/action_public/login.php' );
            $login = new login();
            $login->ipsclass = & $this->ipsclass;
            $login->do_log_out(0);
        }

        //-----------------------------------------
        // Continue
        //-----------------------------------------
        $_SESSION = array_merge($_SESSION, array('coppa_user' => $this->ipsclass->input['coppa_user'],
            'UserName' => $this->ipsclass->input['UserName'],
            'members_display_name' => $this->ipsclass->input['members_display_name'],
            'day' => $this->ipsclass->input['day'],
            'month' => $this->ipsclass->input['month'],
            'year' => $this->ipsclass->input['year'],
            'EmailAddress' => $this->ipsclass->input['EmailAddress'],
            'EmailAddress_two' => $this->ipsclass->input['EmailAddress_two'],
            'PassWord' => $this->ipsclass->input['PassWord'],
            'PassWord_Check' => $this->ipsclass->input['PassWord_Check'],
            'country' => $this->ipsclass->input['country'],
            'city' => $this->ipsclass->input['city'],
            'district' => $this->ipsclass->input['district'],
            'ward' => $this->ipsclass->input['ward'],
            'address' => $this->ipsclass->input['address'],
            'siteLocation' => $this->ipsclass->input['siteLocation']
                )
        );


        // Set referer to redirect user back to their current page before they click on register link
        if (trim($this->ipsclass->input['referer']))
            $_SESSION['referer'] = $this->ipsclass->input['referer'];

        require_once( ROOT_PATH . 'sources/classes/class_custom_fields.php' );
        $fields = new custom_fields($this->ipsclass->DB);

        $fields->cache_data = $this->ipsclass->cache['profilefields'];

        $fields->init_data();
        $fields->parse_to_register();

        foreach ($fields->out_fields as $id => $data) {
            $_SESSION['field_' . $id] = $this->ipsclass->input['field_' . $id];
        }

        //-----------------------------------------
        // Clean out anti-spam stuffy
        //-----------------------------------------

        if ($this->ipsclass->vars['bot_antispam']) {
            // Set a new ID for this reg request...

            $regid = md5(uniqid(microtime()));

            if ($this->ipsclass->vars['bot_antispam'] == 'gd') {
                //-----------------------------------------
                // Get 6 random chars
                //-----------------------------------------

                $reg_code = strtoupper(substr(md5(mt_rand()), 0, 6));
            } else {
                //-----------------------------------------
                // Set a new 6 character numerical string
                //-----------------------------------------

                $reg_code = mt_rand(100000, 999999);
            }

            // Insert into the DB

            $this->ipsclass->DB->do_insert('reg_antispam', array(
                'regid' => $regid,
                'regcode' => $reg_code,
                'ip_address' => $this->ipsclass->input['IP_ADDRESS'],
                'ctime' => time(),
            ));
        }

        $cache = $this->ipsclass->DB->simple_exec_query(array('select' => '*', 'from' => 'conf_settings', 'where' => "conf_key='reg_rules'"));

        $text = $cache['conf_value'] ? $cache['conf_value'] : $cache['conf_default'];

        // Update by tuanhnm 
        // Check is short register state
        if ($short_register) {
            $this->short_register();
            exit();
        }

        $url_regi = $this->ipsclass->base_url;
        echo "&errorStatus=0";
        echo "&urlRegister=" . $url_regi;
        exit();
        $this->output .= $this->ipsclass->compiled_templates['skin_regportal']->show_terms($this->ipsclass->my_nl2br($text), $coppa);


        if ($this->ipsclass->vars['bot_antispam'] == 'gd') {
            $this->output = str_replace("<!--{REG.ANTISPAM}-->", $this->ipsclass->compiled_templates['skin_regportal']->bot_antispam_gd($regid, $reg_code_err_msg), $this->output);
        } else if ($this->ipsclass->vars['bot_antispam'] == 'gif') {
            $this->output = str_replace("<!--{REG.ANTISPAM}-->", $this->ipsclass->compiled_templates['skin_regportal']->bot_antispam($regid), $this->output);
        }

        if ($this->ipsclass->vars['bot_antispam'] == 'gd') {
            $this->output = str_replace("<!--{REG.ANTISPAM}-->", $this->ipsclass->compiled_templates['skin_regportal']->bot_antispam_gd($regid, $reg_code_err_msg), $this->output);
        } else if ($this->ipsclass->vars['bot_antispam'] == 'gif') {
            $this->output = str_replace("<!--{REG.ANTISPAM}-->", $this->ipsclass->compiled_templates['skin_regportal']->bot_antispam($regid), $this->output);
        }

        $this->page_title = $this->ipsclass->lang['page_title'];
        $this->nav = array($this->ipsclass->lang['page_title']);
    }

    //-------------------------------------------
    // Begin short_register
    //-------------------------------------------
    function short_register() {
        //-----------------------------------------
        // INIT
        //-----------------------------------------

        if ($this->ipsclass->vars['ipbli_usertype'] == 'email') {
            $this->ipsclass->input['UserName'] = $this->ipsclass->input['members_display_name'];
        }

        $form_errors = array();
        $coppa = ($this->ipsclass->input['coppa_user'] == 1) ? 1 : 0;
        $in_username = str_replace('|', '&#124;', $this->ipsclass->input['UserName']);
        $in_password = trim($this->ipsclass->input['PassWord']);
        $in_email = strtolower(trim($this->ipsclass->input['EmailAddress']));
        $banfilters = array();
        $members_display_name = trim($this->ipsclass->input['members_display_name']);

        //-----------------------------------------
        // Build up the hashes
        //-----------------------------------------

        $mem_group = $this->ipsclass->vars['member_group'];

        //-----------------------------------------
        // Are we asking the member or admin to preview?
        //-----------------------------------------

        if ($this->ipsclass->vars['reg_auth_type']) {
            $mem_group = $this->ipsclass->vars['auth_group'];
        } else if ($coppa == 1) {
            $mem_group = $this->ipsclass->vars['auth_group'];
        } else if ($this->ipsclass->vars['subsm_enforce']) {
            $mem_group = $this->ipsclass->vars['subsm_nopkg_group'];
        }

        $_mke_time = ( $this->ipsclass->vars['login_key_expire'] ) ? ( time() + ( intval($this->ipsclass->vars['login_key_expire']) * 86400 ) ) : 0;

        $member = array(
            'name' => $in_username,
            'members_l_username' => strtolower($in_username),
            'members_display_name' => $this->ipsclass->vars['auth_allow_dnames'] ? $members_display_name : $in_username,
            'members_l_display_name' => strtolower($this->ipsclass->vars['auth_allow_dnames'] ? $members_display_name : $in_username ),
            'member_login_key' => $this->ipsclass->converge->generate_auto_log_in_key(),
            'member_login_key_expire' => $_mke_time,
            'email' => $in_email,
            'mgroup' => $mem_group,
            'posts' => 0,
            'joined' => time(),
            'ip_address' => $this->ipsclass->ip_address,
            'time_offset' => $this->ipsclass->input['time_offset'],
            'view_sigs' => 1,
            'email_pm' => 1,
            'view_img' => 1,
            'view_avs' => 1,
            'restrict_post' => 0,
            'view_pop' => 1,
            'msg_total' => 0,
            'new_msg' => 0,
            'coppa_user' => $coppa,
            'language' => $this->ipsclass->vars['default_language'],
            'members_auto_dst' => 1,
            'members_editor_choice' => $this->ipsclass->vars['ips_default_editor'],
            'allow_admin_mails' => intval($this->ipsclass->input['allow_admin_mail']),
            'hide_email' => $this->ipsclass->input['allow_member_mail'] ? 0 : 1,
            'subs_pkg_chosen' => intval($this->ipsclass->input['subspackage'])
        );

        //-----------------------------------------
        // Insert: CONVERGE
        //-----------------------------------------

        $salt = $this->ipsclass->converge->generate_password_salt(5);
        $passhash = $this->ipsclass->converge->generate_compiled_passhash($salt, md5($in_password));

        $converge = array('converge_email' => $in_email,
            'converge_joined' => time(),
            'converge_pass_hash' => $passhash,
            'converge_pass_salt' => str_replace('\\', "\\\\", $salt)
        );

        //-----------------------------------------
        // Add Converge: Member
        //-----------------------------------------
        $this->han_login->create_account(array('email' => $member['email'],
            'joined' => $member['joined'],
            'password' => $in_password,
            'ip_address' => $this->ipsclass->ip_address
        ));

        if ($this->han_login->return_code != 'METHOD_NOT_DEFINED' AND $this->han_login->return_code != 'SUCCESS') {
            $this->ipsclass->Error(array('LEVEL' => 5, 'MSG' => 'han_login_create_failed', 'EXTRA' => $this->han_login->return_details ? $this->han_login->return_details : $this->han_login->return_code));
        }

        $this->ipsclass->DB->do_insert('members_converge', $converge);

        //-----------------------------------------
        // Get converges auto_increment user_id
        //-----------------------------------------
        $member_id = $this->ipsclass->DB->get_insert_id();
        $member['id'] = $member_id;

        //-----------------------------------------
        // Insert: MEMBERS
        //-----------------------------------------
        $this->ipsclass->DB->force_data_type = array('name' => 'string', 'members_display_name' => 'string', 'members_l_username' => 'string', 'members_l_display_name' => 'string');

        $this->ipsclass->DB->do_insert('members', $member);

        //-----------------------------------------
        // Insert: MEMBER EXTRA
        //-----------------------------------------
        $this->ipsclass->DB->do_insert('member_extra', array('id' => $member_id,
            'vdirs' => 'in:Inbox|sent:Sent Items',
            'interests' => '',
            'signature' => '',
            'location' => $this->ipsclass->site_info['site_name']
        ));

        if ($_FILES['upload_avatar']['name'] != '' || $_FILES['upload_photo']['name'] != '') {
            require_once ROOT_PATH . "sources/lib/func_usercp.php";
            $this->lib = new func_usercp();
            $this->ipsclass->member = $member;
            $this->ipsclass->member['g_edit_profile'] = 1;
            $this->ipsclass->member['g_avatar_upload'] = 1;
            $this->lib->ipsclass = &$this->ipsclass;
        }

        if ($_FILES['upload_avatar']['name'] != '' || $_FILES['upload_photo']['name'] != '') {
            $this->ipsclass->member = $this->ipsclass->sess->authorise();
        }

        //-----------------------------------------
        // Insert into the custom profile fields DB
        //-----------------------------------------
        $this->ipsclass->DB->do_delete('pfields_content', 'member_id=' . $member['id']);

        $this->ipsclass->DB->force_data_type = array();

        foreach ($fields->out_fields as $_field => $_data) {
            $this->ipsclass->DB->force_data_type[$_field] = 'string';
        }

        $fields->out_fields['member_id'] = $member['id'];

        $this->ipsclass->DB->do_insert('pfields_content', $fields->out_fields);

        //-----------------------------------------
        // Use modules?
        //-----------------------------------------

        if (USE_MODULES == 1) {
            $this->modules->register_class($this);

            $member['password'] = trim($this->ipsclass->input['PassWord']);

            $this->modules->on_create_account($member);

            if ($this->modules->error == 1) {
                return;
            }

            $member['password'] = "";
        }

        //-----------------------------------------
        // Validation key
        //-----------------------------------------
        $validate_key = md5($this->ipsclass->make_password() . time());
        $time = time();

        if ($coppa != 1) {
            if (($this->ipsclass->vars['reg_auth_type'] == 'user' ) or
                    ($this->ipsclass->vars['reg_auth_type'] == 'admin') or
                    ($this->ipsclass->vars['reg_auth_type'] == 'admin_user')) {
                //-----------------------------------------
                // We want to validate all reg's via email,
                // after email verificiation has taken place,
                // we restore their previous group and remove the validate_key
                //-----------------------------------------

                $this->ipsclass->DB->do_insert('validating', array(
                    'vid' => $validate_key,
                    'member_id' => $member['id'],
                    'real_group' => $this->ipsclass->vars['subsm_enforce'] ? $this->ipsclass->vars['subsm_nopkg_group'] : $this->ipsclass->vars['member_group'],
                    'temp_group' => $this->ipsclass->vars['auth_group'],
                    'entry_date' => $time,
                    'coppa_user' => $coppa,
                    'new_reg' => 1,
                    'ip_address' => $member['ip_address']
                ));


                if ($this->ipsclass->vars['reg_auth_type'] == 'user' OR $this->ipsclass->vars['reg_auth_type'] == 'admin_user') {
                    $this->email->get_template("reg_validate");

                    $this->email->build_message(array(
                        'THE_LINK' => $this->base_url_nosess . "?act=Reg&CODE=03&uid=" . urlencode($member_id) . "&aid=" . urlencode($validate_key),
                        'NAME' => $member['members_display_name'],
                        'MAN_LINK' => $this->base_url_nosess . "?act=Reg&CODE=05",
                        'EMAIL' => $member['email'],
                        'ID' => $member_id,
                        'CODE' => $validate_key,
                            )
                    );

                    $this->email->subject = $this->ipsclass->lang['new_registration_email'] . $this->ipsclass->vars['board_name'];
                    $this->email->to = $member['email'];

                    $this->email->send_mail();

                    $this->output = $this->ipsclass->compiled_templates['skin_register']->show_authorise($member);
                } else if ($this->ipsclass->vars['reg_auth_type'] == 'admin') {
                    $this->output = $this->ipsclass->compiled_templates['skin_register']->show_preview($member);
                }

                if ($this->ipsclass->vars['new_reg_notify']) {

                    $date = $this->ipsclass->get_date(time(), 'LONG', 1);

                    $this->email->get_template("admin_newuser");

                    $this->email->build_message(array(
                        'DATE' => $date,
                        'MEMBER_NAME' => $member['members_display_name'],
                            )
                    );

                    $this->email->subject = $this->ipsclass->lang['new_registration_email1'] . $this->ipsclass->vars['board_name'];
                    $this->email->to = $this->ipsclass->vars['email_in'];
                    $this->email->send_mail();
                }

                $this->page_title = $this->ipsclass->lang['reg_success'];

                $this->nav = array($this->ipsclass->lang['nav_reg']);
            } else {
                //-----------------------------------------
                // We don't want to preview, or get them to validate via email.
                //-----------------------------------------

                $this->ipsclass->cache['stats']['last_mem_name'] = $member['members_display_name'];
                $this->ipsclass->cache['stats']['last_mem_id'] = $member['id'];
                // Added by BabyWolf
                $this->ipsclass->cache['stats']['last_mem_username'] = $member['name'];
                $this->ipsclass->cache['stats']['mem_count'] += 1;

                $this->ipsclass->update_cache(array('name' => 'stats', 'array' => 1, 'deletefirst' => 0));

                if ($this->ipsclass->vars['new_reg_notify']) {
                    $date = $this->ipsclass->get_date(time(), 'LONG', 1);

                    $this->email->get_template("admin_newuser");

                    $this->email->build_message(array(
                        'DATE' => $date,
                        'MEMBER_NAME' => $member['members_display_name'],
                            )
                    );

                    $this->email->subject = $this->ipsclass->lang['new_registration_email1'] . $this->ipsclass->vars['board_name'];
                    $this->email->to = $this->ipsclass->vars['email_in'];
                    $this->email->send_mail();
                }

                $this->ipsclass->no_print_header = 0;

                $this->ipsclass->my_setcookie("pass_hash", $member['member_login_key'], 1);
                $this->ipsclass->my_setcookie("member_id", $member['id'], 1);
                $this->ipsclass->my_setcookie('session_id', '0', -1);

                $this->ipsclass->stronghold_set_cookie($member['id'], $member['member_login_key']);
                
                $url = "{$this->ipsclass->vars['profile_url']}/index.php?";
                $act = 'regportal';
                $code = 'wg';
                echo "&errorStatus=0";
                echo "&urlRegister=" . $url;
                echo "&act=" . $act;
                echo "&CODE=" . $code;

                //$this->ipsclass->boink_it($this->ipsclass->base_url . '&act=login&CODE=autologin&fromreg=1');
            }
        } else {
            // This is a COPPA user, so lets tell them they registered OK and redirect to the form.

            $this->ipsclass->DB->do_insert('validating', array(
                'vid' => $validate_key,
                'member_id' => $member['id'],
                'real_group' => $this->ipsclass->vars['member_group'],
                'temp_group' => $this->ipsclass->vars['auth_group'],
                'entry_date' => $time,
                'coppa_user' => $coppa,
                'new_reg' => 1,
                'ip_address' => $member['ip_address']
            ));

            $url = "{$this->ipsclass->vars['profile_url']}/index.php?";
            $act = 'regportal';
            $code = 'wg';
            echo "&errorStatus=0";
            echo "&urlRegister=" . $url;
            echo "&act=" . $act;
            echo "&CODE=" . $code;

            //$this->ipsclass->print->redirect_screen($this->ipsclass->lang['cp_success'], 'act=Reg&amp;CODE=12');
        }
    }

    //--------------------------------------------
    // Begin regportal_process
    //--------------------------------------------
    function regportal_process() {
        //-----------------------------------------
        // INIT
        //-----------------------------------------
        // First get parameters from session
        $this->ipsclass->input = array_merge($this->ipsclass->input, $_SESSION);

        $form_errors = array();
        $coppa = ($this->ipsclass->input['coppa_user'] == 1) ? 1 : 0;
        $in_username = str_replace('|', '&#124;', $this->ipsclass->input['UserName']);
        $in_password = trim($this->ipsclass->input['PassWord']);
        $in_email = strtolower(trim($this->ipsclass->input['EmailAddress']));
        $banfilters = array();
        $members_display_name = trim($this->ipsclass->input['members_display_name']);

        //-----------------------------------------
        // Did we agree to the t&c?
        //-----------------------------------------

        if (!$this->ipsclass->input['agree_to_terms']) {
            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'reg_no_agree', 'EXTRA' => $this->ipsclass->base_url));
        }

        //-----------------------------------------
        // Check the reg_code
        //-----------------------------------------
        $reg_code_err_msg = "";

        if ($this->ipsclass->vars['bot_antispam']) {
            if ($this->ipsclass->input['regid'] == "") {
                $reg_code_err_msg = $this->ipsclass->lang['err_reg_code'];
            } else {
                $this->ipsclass->DB->build_query(array('select' => '*',
                    'from' => 'reg_antispam',
                    'where' => "regid='" . trim($this->ipsclass->txt_alphanumerical_clean($this->ipsclass->input['regid'])) . "'"
                ));

                $this->ipsclass->DB->exec_query();

                if (!$row = $this->ipsclass->DB->fetch_row()) {
                    $reg_code_err_msg = $this->ipsclass->lang['err_reg_code'];
                } else if (trim($this->ipsclass->txt_alphanumerical_clean($this->ipsclass->input['reg_code'])) != $row['regcode']) {
                    $reg_code_err_msg = $this->ipsclass->lang['err_reg_code'];
                }
                $this->ipsclass->DB->do_delete('reg_antispam', "regid='" . trim($this->ipsclass->txt_alphanumerical_clean($this->ipsclass->input['regid'])) . "'");
            }
        }

        //-----------------------------------------
        // CHECK 2: Any errors (duplicate names, etc)?
        //-----------------------------------------

        if ($reg_code_err_msg) {
            $this->show_terms_read($reg_code_err_msg);
            return;
        }

        //-----------------------------------------
        // Build up the hashes
        //-----------------------------------------

        $mem_group = $this->ipsclass->vars['member_group'];

        //-----------------------------------------
        // Are we asking the member or admin to preview?
        //-----------------------------------------

        if ($this->ipsclass->vars['reg_auth_type']) {
            $mem_group = $this->ipsclass->vars['auth_group'];
        } else if ($coppa == 1) {
            $mem_group = $this->ipsclass->vars['auth_group'];
        } else if ($this->ipsclass->vars['subsm_enforce']) {
            $mem_group = $this->ipsclass->vars['subsm_nopkg_group'];
        }

        $_mke_time = ( $this->ipsclass->vars['login_key_expire'] ) ? ( time() + ( intval($this->ipsclass->vars['login_key_expire']) * 86400 ) ) : 0;

        //-----------------------------------------
        // make sure that either we entered
        // all calendar fields, or we left them
        // all blank
        //-----------------------------------------		
        $c_cnt = 0;

        foreach (array('day', 'month', 'year') as $v) {
            if (!empty($this->ipsclass->input[$v])) {
                $c_cnt++;
            }
        }

        if (($c_cnt > 0) and ($c_cnt != 3)) {
            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'calendar_not_all'));
        } else if (($c_cnt > 0) and ($c_cnt == 3)) {
            //-----------------------------------------
            // Make sure it's a legal date
            //-----------------------------------------

            $_year = $this->ipsclass->input['year'] ? $this->ipsclass->input['year'] : 1999;

            if (!checkdate($this->ipsclass->input['month'], $this->ipsclass->input['day'], $_year)) {
                $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'ucp_birthday_legal_date'));
            }
        }

        $member = array(
            'name' => $in_username,
            'members_l_username' => strtolower($in_username),
            'members_display_name' => $this->ipsclass->vars['auth_allow_dnames'] ? $members_display_name : $in_username,
            'members_l_display_name' => strtolower($this->ipsclass->vars['auth_allow_dnames'] ? $members_display_name : $in_username ),
            'member_login_key' => $this->ipsclass->converge->generate_auto_log_in_key(),
            'member_login_key_expire' => $_mke_time,
            'email' => $in_email,
            'mgroup' => $mem_group,
            'posts' => 0,
            'joined' => time(),
            'ip_address' => $this->ipsclass->ip_address,
            'time_offset' => $this->ipsclass->input['time_offset'],
            'view_sigs' => 1,
            'email_pm' => 1,
            'view_img' => 1,
            'view_avs' => 1,
            'restrict_post' => 0,
            'view_pop' => 1,
            'msg_total' => 0,
            'new_msg' => 0,
            'coppa_user' => $coppa,
            'language' => $this->ipsclass->vars['default_language'],
            'members_auto_dst' => 1,
            'members_editor_choice' => $this->ipsclass->vars['ips_default_editor'],
            'allow_admin_mails' => 1,
            'hide_email' => 1,
            'subs_pkg_chosen' => intval($this->ipsclass->input['subspackage']),
            'bday_day' => $this->ipsclass->input['day'],
            'bday_month' => $this->ipsclass->input['month'],
            'bday_year' => $this->ipsclass->input['year'],
            'members_country' => substr($this->ipsclass->input['country'], strpos($this->ipsclass->input['country'], '|') + 1),
            'members_city' => substr($this->ipsclass->input['city'], strpos($this->ipsclass->input['city'], '|') + 1),
            'members_district' => substr($this->ipsclass->input['district'], strpos($this->ipsclass->input['district'], '|') + 1),
            'members_ward' => $this->ipsclass->input['ward'],
            'members_address' => $this->ipsclass->input['address']
        );

        //-----------------------------------------
        // Insert: CONVERGE
        //-----------------------------------------
        //print_r ($member);
        //exit();

        $salt = $this->ipsclass->converge->generate_password_salt(5);
        $passhash = $this->ipsclass->converge->generate_compiled_passhash($salt, md5($in_password));

        $converge = array('converge_email' => $in_email,
            'converge_joined' => time(),
            'converge_pass_hash' => $passhash,
            'converge_pass_salt' => str_replace('\\', "\\\\", $salt)
        );

        //-----------------------------------------
        // Add Converge: Member
        //-----------------------------------------
        //-----------------------------------------
        // Load handler...
        //-----------------------------------------

        require_once( ROOT_PATH . 'sources/handlers/han_login.php' );
        $this->han_login = new han_login();
        $this->han_login->ipsclass = & $this->ipsclass;
        $this->han_login->init();

        $this->han_login->create_account(array('email' => $member['email'],
            'joined' => $member['joined'],
            'password' => $in_password,
            'ip_address' => $this->ipsclass->ip_address
        ));

        //echo 'RETURN CODE : '.$this->han_login->return_code;
        //exit();

        if ($this->han_login->return_code != 'METHOD_NOT_DEFINED' AND $this->han_login->return_code != 'SUCCESS') {
            $this->ipsclass->Error(array('LEVEL' => 5, 'MSG' => 'han_login_create_failed', 'EXTRA' => $this->han_login->return_details ? $this->han_login->return_details : $this->han_login->return_code));
        }

        $this->ipsclass->DB->do_insert('members_converge', $converge);

        //-----------------------------------------
        // Get converges auto_increment user_id
        //-----------------------------------------

        $member_id = $this->ipsclass->DB->get_insert_id();
        $member['id'] = $member_id;

        //-----------------------------------------
        // Insert: MEMBERS
        //-----------------------------------------
        $this->ipsclass->DB->force_data_type = array('name' => 'string', 'members_display_name' => 'string', 'members_l_username' => 'string', 'members_l_display_name' => 'string');

        $this->ipsclass->DB->do_insert('members', $member);

        //-----------------------------------------
        // Insert: MEMBER EXTRA
        //-----------------------------------------
        $this->ipsclass->DB->do_insert('member_extra', array('id' => $member_id,
            'vdirs' => 'in:Inbox|sent:Sent Items',
            'interests' => '',
            'signature' => '',
            'location' => $this->ipsclass->input['siteLocation']));

        // Insert chosen gender
        $_gender = $this->ipsclass->input['gender'] == 'male' ? 'male' : ( $this->ipsclass->input['gender'] == 'female' ? 'female' : '' );
        $this->ipsclass->DB->do_insert('profile_portal', array('pp_gender' => $_gender, 'pp_member_id' => $member['id']));

        //-----------------------------------------
        // Insert into the custom profile fields DB
        //-----------------------------------------
        // Ensure deleted members profile fields are removed.

        $this->ipsclass->DB->do_delete('pfields_content', 'member_id=' . $member['id']);

        $this->ipsclass->DB->force_data_type = array();

        //-----------------------------------------
        // Custom profile field stuff
        //-----------------------------------------

        require_once( ROOT_PATH . 'sources/classes/class_custom_fields.php' );
        $fields = new custom_fields($this->ipsclass->DB);

        $fields->cache_data = $this->ipsclass->cache['profilefields'];

        $fields->init_data();
        $fields->parse_to_save(1);

        foreach ($fields->out_fields as $_field => $_data) {
            $this->ipsclass->DB->force_data_type[$_field] = 'string';
        }

        $fields->out_fields['member_id'] = $member['id'];

        $this->ipsclass->DB->do_insert('pfields_content', $fields->out_fields);

        //-----------------------------------------
        // Use modules?
        //-----------------------------------------
        //echo 'USE MODULES : '.USE_MODULES;
        //exit();
        //exit();

        if (USE_MODULES == 1) {

            echo 'ha ha USE_MODULES';

            $this->modules->register_class($this);

            echo 'under USE_MODULES';

            $member['password'] = trim($this->ipsclass->input['PassWord']);

            $this->modules->on_create_account($member);

            if ($this->modules->error == 1) {
                echo 'in modules error';
                //************************
                // Updated by tuanhnm
                // on 06/08/2011
                // *********************
                $url = "{$this->ipsclass->vars['profile_url']}/{$this->ipsclass->member['name']}/{$this->ipsclass->lang['seoPanelPage']}{$this->ipsclass->lang['seoPageSuffix']}";
                //$this->ipsclass->boink_it("{$this->ipsclass->vars['profile_url']}/{$this->ipsclass->vars['name']}/{$this->ipsclass->vars['seoPanelPage']}{$this->ipsclass->vars['seoPageSuffix']}");
                //$this->ipsclass->print->redirect_screen( $this->ipsclass->lang['cp_success'], 'act=Reg&amp;CODE=12' );
                $this->ipsclass->print->redirect_screen($url);

                return;
            }

            //echo 'in USE_MODULES';
            //exit();
            //********
            // Updatedby tuanhnm
            // fixed tempature, not remove please
            //*********
            //$url = $this->ipsclass->vars['profile_url']."/index.php?act=regportal&CODE=wg";
            //$this->ipsclass->print->redirect_screen( $this->ipsclass->lang['cp_success'], 'act=Reg&amp;CODE=12' );
            //$this->ipsclass->boink_it($this->ipsclass->base_url . '&act=regportal&CODE=wg');
            $this->ipsclass->boink_it("{$this->ipsclass->vars['profile_url']}/{$this->ipsclass->member['name']}/{$this->ipsclass->lang['seoPanelPage']}{$this->ipsclass->lang['seoPageSuffix']}");
            return;

            $member['password'] = "";
        }

        //-----------------------------------------
        // Validation key
        //-----------------------------------------

        $validate_key = md5($this->ipsclass->make_password() . time());
        $time = time();

        if ($coppa != 1) {
            if (($this->ipsclass->vars['reg_auth_type'] == 'user' ) or
                    ($this->ipsclass->vars['reg_auth_type'] == 'admin') or
                    ($this->ipsclass->vars['reg_auth_type'] == 'admin_user')) {
                //-----------------------------------------
                // We want to validate all reg's via email,
                // after email verificiation has taken place,
                // we restore their previous group and remove the validate_key
                //-----------------------------------------

                $this->ipsclass->DB->do_insert('validating', array(
                    'vid' => $validate_key,
                    'member_id' => $member['id'],
                    'real_group' => $this->ipsclass->vars['subsm_enforce'] ? $this->ipsclass->vars['subsm_nopkg_group'] : $this->ipsclass->vars['member_group'],
                    'temp_group' => $this->ipsclass->vars['auth_group'],
                    'entry_date' => $time,
                    'coppa_user' => $coppa,
                    'new_reg' => 1,
                    'ip_address' => $member['ip_address']
                ));


                if ($this->ipsclass->vars['reg_auth_type'] == 'user' OR $this->ipsclass->vars['reg_auth_type'] == 'admin_user') {
                    $this->email->get_template("reg_validate");

                    $this->email->build_message(array(
                        'THE_LINK' => $this->base_url_nosess . "?act=Reg&CODE=03&uid=" . urlencode($member_id) . "&aid=" . urlencode($validate_key),
                        'NAME' => $member['members_display_name'],
                        'MAN_LINK' => $this->base_url_nosess . "?act=Reg&CODE=05",
                        'EMAIL' => $member['email'],
                        'ID' => $member_id,
                        'CODE' => $validate_key,
                            )
                    );

                    $this->email->subject = $this->ipsclass->lang['new_registration_email'] . $this->ipsclass->vars['board_name'];
                    $this->email->to = $member['email'];

                    $this->email->send_mail();

                    $this->output = $this->ipsclass->compiled_templates['skin_regportal']->show_authorise($member);
                } else if ($this->ipsclass->vars['reg_auth_type'] == 'admin') {
                    $this->output = $this->ipsclass->compiled_templates['skin_regportal']->show_preview($member);
                }

                if ($this->ipsclass->vars['new_reg_notify']) {

                    $date = $this->ipsclass->get_date(time(), 'LONG', 1);

                    $this->email->get_template("admin_newuser");

                    $this->email->build_message(array(
                        'DATE' => $date,
                        'MEMBER_NAME' => $member['members_display_name'],
                            )
                    );

                    $this->email->subject = $this->ipsclass->lang['new_registration_email1'] . $this->ipsclass->vars['board_name'];
                    $this->email->to = $this->ipsclass->vars['email_in'];
                    $this->email->send_mail();
                }

                $this->page_title = $this->ipsclass->lang['reg_success'];

                $this->nav = array($this->ipsclass->lang['nav_reg']);
            } else {
                //-----------------------------------------
                // We don't want to preview, or get them to validate via email.
                //-----------------------------------------

                $this->ipsclass->cache['stats']['last_mem_name'] = $member['members_display_name'];
                $this->ipsclass->cache['stats']['last_mem_id'] = $member['id'];
                // Added by BabyWolf
                $this->ipsclass->cache['stats']['last_mem_username'] = $member['name'];
                // Updated by BabyWolf
                //$this->ipsclass->cache['stats']['mem_count']    += 1;
                $this->ipsclass->cache['stats']['mem_count'] = $member['id'];

                $this->ipsclass->update_cache(array('name' => 'stats', 'array' => 1, 'deletefirst' => 0));

                if ($this->ipsclass->vars['new_reg_notify']) {
                    $date = $this->ipsclass->get_date(time(), 'LONG', 1);

                    $this->email->get_template("admin_newuser");

                    $this->email->build_message(array(
                        'DATE' => $date,
                        'MEMBER_NAME' => $member['members_display_name'],
                            )
                    );
                    $this->email->subject = $this->ipsclass->lang['new_registration_email1'] . $this->ipsclass->vars['board_name'];
                    $this->email->to = $this->ipsclass->vars['email_in'];
                    $this->email->send_mail();
                }
                $this->ipsclass->no_print_header = 0;

                $this->ipsclass->my_setcookie("pass_hash", $member['member_login_key'], 1);
                $this->ipsclass->my_setcookie("member_id", $member['id'], 1);
                $this->ipsclass->my_setcookie('session_id', '0', -1);

                $this->ipsclass->stronghold_set_cookie($member['id'], $member['member_login_key']);

                $this->ipsclass->boink_it($this->ipsclass->base_url . '&act=login&CODE=autologin&fromreg=1');
            }
        } else {
            // This is a COPPA user, so lets tell them they registered OK and redirect to the form.

            $this->ipsclass->DB->do_insert('validating', array(
                'vid' => $validate_key,
                'member_id' => $member['id'],
                'real_group' => $this->ipsclass->vars['member_group'],
                'temp_group' => $this->ipsclass->vars['auth_group'],
                'entry_date' => $time,
                'coppa_user' => $coppa,
                'new_reg' => 1,
                'ip_address' => $member['ip_address']
            ));
            // ****************
            // Update by tuanhm 
            // On 06/08/2011
            //****************
            $url = "{$this->ipsclass->vars['profile_url']}/{$this->ipsclass->member['name']}/{$this->ipsclass->lang['seoPanelPage']}{$this->ipsclass->lang['seoPageSuffix']}";
            
            //$this->ipsclass->print->redirect_screen( $this->ipsclass->lang['cp_success'], 'act=Reg&amp;CODE=12' );
            $this->ipsclass->print->redirect_screen($url);
        }
    }

    //--------------------------------------------
    // Begin show_search_result
    //--------------------------------------------
    function show_search_result() {
        require_once(KERNEL_PATH . "search.class.php");

        $page = max(1, intval($this->ipsclass->input['page']));
        $keyword = str_replace('-', ' ', $this->ipsclass->input['keyword']);
        $title = search::convertUnicode($keyword); //.' - Even Tim Kiem';	
        list($arrData, $total) = search::getContentToAPIGoogle($keyword, $page);
        $strHTML = '';
        //print_r($arrData); exit;
        foreach ($arrData as $k => $itemWeb) {
            $strHTML.="<div class=\"rp-result-content\"><p><a target=\"_blank\" href=\"$itemWeb->unescapedUrl\" rel=\"nofollow\">$itemWeb->title</a></p><p>$itemWeb->content</p><p><span>$itemWeb->visibleUrl</span></p></div>";
        }
        $strUrlPage = $this->ipsclass->vars['profile_url'] . "/search/%s%/" . $this->ipsclass->input['keyword'] . '.html';
        $strEvent = '';
        $this->page_title = $keyword . ' | ' . $title . ' - ' . $this->ipsclass->lang['search_title'];
        list($strPage, $strResult) = search::getPagesLinks($total, $page, 8, $strUrlPage, $strEvent, '', false);

        $this->output = $this->ipsclass->compiled_templates['skin_regportal']->search_result_page($keyword, $strHTML, $strPage, $strResult);
    }

    //--------------------------------------------
    // Begin import_members
    //--------------------------------------------
    function import_members() {
        $start = intval($_GET['num']);
        $vol = 1;

        if ($start >= 13227) {
            echo "success";
            exit();
        }
        if ($start == $_GET['max'])
            exit();

        $this->ipsclass->DB->simple_construct(array('select' => '*',
            'from' => 'accounts',
            'order' => 'id',
            'limit' => array($start, $vol)
                )
        );

        $this->ipsclass->DB->simple_exec();
        error_reporting(E_ALL);
        $count = $start + 1;
        while ($result = $this->ipsclass->DB->fetch_row()) {
            echo $name = $result['name'];
            echo $pass = "maplenopass";
            echo $email = "maple" . $count . "@even.vn";
            $this->create_account($name, $pass, $email);

            echo "Inserted " . $name . " <br />";
            echo $count++;
        }

        echo "Completed " . $start;
        $url = $this->ipsclass->vars['board_url'] . "/index.php?act=regportal&CODE=import_members&num=" . ($start + $vol) . "&max=" . $_GET['max'];

        header("refresh:1;url=" . $url);
        echo 'You\'ll be redirected in about 1 secs. If not, click <a href="wherever.php">here</a>.';
        exit();
    }

    //--------------------------------------------
    // Begin fix_member_data
    //--------------------------------------------
    function fix_member_data() {
        $start = intval($_GET['num']);
        $vol = 1;

        if ($start >= 13226) {
            echo "success";
            exit();
        }
        if ($start == $_GET['max'])
            exit();

        $this->ipsclass->DB->simple_construct(array('select' => '*',
            'from' => 'members',
            'where' => 'maple_check=2',
            'order' => 'id',
            'limit' => array($start, $vol)
                )
        );

        $this->ipsclass->DB->simple_exec();

        //-----------------------------------------
        // Custom profile field stuff
        //-----------------------------------------

        require_once( ROOT_PATH . 'sources/classes/class_custom_fields.php' );
        $fields = new custom_fields($this->ipsclass->DB);

        $fields->cache_data = $this->ipsclass->cache['profilefields'];

        $fields->init_data();
        $fields->parse_to_save(1);

        foreach ($fields->out_fields as $_field => $_data) {
            $this->ipsclass->DB->force_data_type[$_field] = 'string';
        }

        error_reporting(E_ALL);
        while ($result = $this->ipsclass->DB->fetch_row()) {
            $fields->out_fields['member_id'] = $result['id'];
            $this->ipsclass->DB->do_insert('pfields_content', $fields->out_fields);
            echo "Inserted for member " . $result['name'] . " <br />";
        }

        echo "Completed " . $start;
        $url = $this->ipsclass->vars['board_url'] . "/index.php?act=regportal&CODE=fix_member_data&num=" . ($start + $vol) . "&max=" . $_GET['max'];

        header("refresh:1;url=" . $url);
        echo 'You\'ll be redirected in about 1 secs. If not, click <a href="wherever.php">here</a>.';
        exit();
    }

    //-----------------------------------------
    // Begin my_show_page_cpanel
    //-----------------------------------------    	
    function my_show_page_cpanel($form_errors=array()) {

        //echo "sdsdsd";exit();
        //load skin
        $this->ipsclass->load_template('skin_regportal');
        $this->ipsclass->load_language('lang_regportal');
        $this->page_title = $this->ipsclass->lang['socials_title'];
        $this->nav = array($this->ipsclass->lang['socials_title']);
        //-----------------------------------------
        // Check viewing permissions, etc
        //-----------------------------------------
        
        if (!$this->ipsclass->member['id']) {
            
            $this->ipsclass->boink_it($this->ipsclass->vars['profile_url']);
        }
        //echo $this->ipsclass->member['id'];exit();
        $_member_ids = array();
        $friends[] = array();
        $comments[] = array();
        $sql_extra = '';
        $member_id = intval($this->ipsclass->member['id']);
        $per_page = intval($this->ipsclass->vars['social_per_page_setting']) <=0 ? 25 :  $this->ipsclass->vars['social_per_page_setting'];
        $start = intval($this->ipsclass->input['st']) >= 0 ? intval($this->ipsclass->input['st']) : 0;
        $member = $this->common->format_member($member_id);
        $friends = $this->common->member_load_friends($member, $per_page, $start);
        $friends = (count($friends) < 2) ? null : array_slice($friends, 1, count($friends) - 1);
        if (is_array($friends)) {
            ksort($friends);
        }
        $datas = $this->common->member_load_comment($member, $per_page, $start, $sql_extra);
        $stats = $this->ipsclass->DB->simple_exec_query(array('select' => 'count(pc.comment_id) as count',
            'from' => 'profile_comments pc',
            'where' => ' pc.comment_by_member_id = ' . $member['id']
                )
        );
        $pages = $this->common->create_customize_paging($stats['count'], $per_page, $start, "", $this->ipsclass->lang['tpl_pages'],'#');
        $comments['pages'] = $pages;
        $comments['total_comments'] = count($datas);
        $comments['datas'] = $datas;
        
        if(count($datas) > 0){
            $layout_comment = $this->ipsclass->compiled_templates['skin_regportal']->content_wg_comment_02($comments);
            $member['layout_comment_display'] = "class='wrapper'";
        }
        
        $own_id = $member['id'];
        
        $member['own_id'] = $own_id;
        
        $member['total_friends'] = count($friends);
        $member['approved_friends'] = $friends;
        $member['layout_comment'] = $layout_comment;

        // Check login 		
        $is_own = $this->ipsclass->member['id'] == $member['id'] ? TRUE : FALSE;
        $this->output = $this->common->load_left_content($member, $is_own, TRUE, FALSE, FALSE);
        $this->output .= $this->ipsclass->compiled_templates['skin_regportal']->content_wg_temp2($member);
        unset($member);
        unset($comments);
        unset($friends);
        unset($layout_comment);
    }

    //-----------------------------------------
    // Created my_show_page_profile 
    //-----------------------------------------    	
    function my_show_page_profile($form_errors=array()) {
        
        //echo "sdsds";exit();
        $this->ipsclass->load_template('skin_regportal');
        $this->ipsclass->load_language('lang_regportal');
        $member_id = 0;
        $guest_id = -1;
        $per_page = intval($this->ipsclass->vars['social_per_page_setting']) <=0 ? 25 :  $this->ipsclass->vars['social_per_page_setting'];
        $start = intval($this->ipsclass->input['st']) >= 0 ? intval($this->ipsclass->input['st']) : 0;
        //echo "dfdfd";exit();
        //-----------------------------------------
        // Check viewing permissions, etc
        //-----------------------------------------

        if($this->ipsclass->input['guest']){
            $member_id = intval($this->ipsclass->input['guest']);
            $guest_id = 1;
        }else if(intval($this->ipsclass->member['id']) > 0 ){
            $member_id = intval($this->ipsclass->member['id']);
            $guest_id = 0;
        }
        //echo $guest_id;exit();
        if ($guest_id == -1) {
            $this->ipsclass->boink_it( $this->ipsclass->base_url );
            exit();
        }

        // Get information member
        $member = $this->common->format_member($member_id);
        
        
//        $member['dkm_Level'] = $this->custom_fields->field_data['Level'];
//        $member['dkm_Icon'] = $this->custom_fields->field_data['dkm_Icon'];
//        $member['dkm_Reputation'] = $this->custom_fields->field_data['dkm_Reputation'];
//        $member['dkm_HP'] = $this->custom_fields->field_data['HP'];
//        $member['dkm_MP'] = $this->custom_fields->field_data['MP'];
//        $member['dkm_EXP'] = $this->custom_fields->field_data['EXP'];
//        $member['dkm_Cash'] = $this->custom_fields->field_data['dkm_Cash'];
//        $this->ipsclass->load_template('skin_topic');
//        $member = $this->ipsclass->parse_member($member);
        $member = $this->common->parseMemberProfile($member);
        //echo ($member['dkm_MP']);
        //exit();
        $member['my_upload_url'] = $this->ipsclass->vars['my_upload_url'];
        $this->ipsclass->member = $member;
        $friends = $this->common->member_load_friends($member, $per_page, $start);
        $friends = (count($friends) < 2) ? null : array_slice($friends, 1, count($friends) - 1);
        if (is_array($friends)) {
            ksort($friends);
        }
        /*
         * Total invite friend
         */
        $member['guest'] = $guest_id;
        $member['own'] = $member['id'];
        $member['member_name'] = $member['name'];
        $member['total_friends'] = count($friends);
        $member['approved_friends'] = $friends;
        //var_dump($member);exit();
        $this->page_title = $this->ipsclass->lang['profile_title'];
        $this->nav = array($this->ipsclass->lang['profile_title']);
        $is_own = $this->ipsclass->member['id'] == $member['id'] ? TRUE : FALSE;
        $this->output = $this->common->load_left_content($member, $is_own, TRUE, FALSE, TRUE);
        $this->output .= $this->ipsclass->compiled_templates['skin_regportal']->content_pf_temp($member);
        unset ($member);
    }

    //-----------------------------------------
    // Created member_approve_friends 
    //-----------------------------------------    	
    function member_approve_friends() {
        $this->ipsclass->load_template('skin_regportal');
        
        //-----------------------------------------
        // Check viewing permissions, etc
        //-----------------------------------------
        $member_id = $this->ipsclass->member['id'];
        $member_id = intval($member_id);
        $per_page = intval($this->ipsclass->vars['social_per_page_setting']) <=0 ? 25 :  $this->ipsclass->vars['social_per_page_setting'];
        $start = intval($this->ipsclass->input['st']) >= 0 ? intval($this->ipsclass->input['st']) : 0;
        $ids = array();
        $friend_approves = array();
        $friends = array();
        $this->ipsclass->DB->flush_query();
        $this->ipsclass->DB->build_query(
                array("select" => "pf.friends_member_id",
                    "from" => 'profile_friends pf',
                    'where'    => "pf.friends_approved = 0 and friends_friend_id = {$member_id} "  ,
                    'order' => 'pf.friends_added DESC'
                )
        );
        $this->ipsclass->DB->exec_query();
        while ($row = $this->ipsclass->DB->fetch_row()) {
            if (!empty($row['friends_member_id'])) {
                $ids[] = $row['friends_member_id'];
            }
        }
        foreach ($ids as $id) {
            $member = $this->common->personal_function_load_member(intval($id));
            $friend_approves[] = $this->common->personal_portal_set_information($member);
        }
        $stats = $this->ipsclass->DB->simple_exec_query( array( 'select' => 'pf.friends_member_id',
                                                                'from'   => 'profile_friends pf',
                                                                'where'    => "pf.friends_approved = 0 and friends_friend_id = {$member_id} and friends_friend_id <> {$this->ipsclass->member['id']}"  ,
                                                                'order' => 'pf.friends_added DESC'
                                                                ) 
                                                        );
        $pages = $this->common->create_customize_paging($stats['count'], $per_page, $start, "", $this->ipsclass->lang['tpl_pages'],'#');
        $friends['owned_id'] = $this->ipsclass->member['id'];
        $friends['datas'] = $friend_approves;
        $friends['pages'] = $pages;
        $friends['total_friends'] = count($friend_approves);
        $layout_comment = $this->ipsclass->compiled_templates['skin_regportal']->owned_load_friend_approves($friends);
        echo $layout_comment;
        exit();
    }

    //-----------------------------------------
    // Created approve_friend
    //----------------------------------------- 
    function approve_friend() {

        $member_id = $this->ipsclass->input['member_id'];
        $friend_id = $this->ipsclass->input['friend_id'];
        if (empty($member_id)) {
            echo "author_fail";
            exit();
        }
        if (empty($friend_id)) {
            echo "not_friend";
            exit();
        }
        $friends_member = array(
            'friends_approved' => 1
        );
        //echo $member_id . "@". $friend_id;exit();
        $this->ipsclass->DB->do_update('profile_friends', $friends_member, " friends_member_id = {$member_id} and friends_friend_id = {$friend_id}");
        echo 'owned_approved_success';
        exit();
    }

    //-----------------------------------------
    // Created logout
    //----------------------------------------- 
    function logout() {
        /*
         * delete cookie
         */
        //-----------------------------------------
        // Set some cookies
        //-----------------------------------------

        $this->ipsclass->my_setcookie("member_id", "0");
        $this->ipsclass->my_setcookie("pass_hash", "0");
        $this->ipsclass->my_setcookie("anonlogin", "-1");

        if (is_array($_COOKIE)) {
            $this->ipsclass->vars['cookie_id'] = preg_quote($this->ipsclass->vars['cookie_id']);

            foreach ($_COOKIE as $cookie => $value) {
                if (preg_match("/^(" . $this->ipsclass->vars['cookie_id'] . "ipbforumpass_.*$)/i", $cookie, $match)) {
                    $this->ipsclass->my_setcookie(str_replace($this->ipsclass->vars['cookie_id'], "", $match[0]), '-', -1);
                }
            }
        }
        //-----------------------------------------
        // Remote log out?
        //-----------------------------------------

        require_once( ROOT_PATH . 'sources/handlers/han_login.php' );
        $this->han_login = new han_login();
        $this->han_login->ipsclass = & $this->ipsclass;
        $this->han_login->init();

        $this->ipsclass->DB->simple_construct(array('update' => 'sessions',
            'set' => "member_name='',member_id='0',login_type='0',member_group={$this->ipsclass->vars['guest_group']}",
            'where' => "id='" . $this->ipsclass->sess->session_id . "'"
        ));

        $this->ipsclass->DB->simple_shutdown_exec();
        list( $privacy, $loggedin ) = explode('&', $this->ipsclass->member['login_anonymous']);

        $this->ipsclass->DB->simple_construct(array('update' => 'members',
            'set' => "login_anonymous='{$privacy}&0', last_visit=" . time() . ", last_activity=" . time(),
            'where' => "id=" . intval($this->ipsclass->member['id'])
                )
        );

        $this->ipsclass->DB->simple_shutdown_exec();
        $this->ipsclass->boink_it($this->ipsclass->vars['profile_url']);
    }

    //-----------------------------------------
    // Created load_all_friends
    //----------------------------------------- 
    function load_all_friends() {
//        //load skin
        //echo $this->common->load_friends();
        //exit();
        $this->ipsclass->load_template('skin_regportal');
        //$per_page = 1;
        $per_page = intval($this->ipsclass->vars['social_per_page_setting']) <=0 ? 25 :  $this->ipsclass->vars['social_per_page_setting'];
        $start = intval($this->ipsclass->input['st']) >= 0 ? intval($this->ipsclass->input['st']) : 0;
        if(intval($this->ipsclass->input['friend_id']) > 0){
            $id = intval($this->ipsclass->input['friend_id']);
        }else{
            $id = intval($this->ipsclass->member['id']);
        }
        $member = $this->common->format_member($id);
        $query = " ( pf.friends_member_id = {$member['id']} or pf.friends_friend_id = {$member['id']})  AND pf.friends_approved = 1 AND  m.id <> {$member['id']} group by concat( m.id )";
        $stats = $this->ipsclass->DB->simple_exec_query(
                array('select' => ' pf.*',
                    'from' => array('profile_friends' => 'pf'),
                    'where' => $query,
                    'limit' => array($start, $per_page),
                    'add_join' => array(0 => array('select' => 'm.*',
                            'from' => array('members' => 'm'),
                            'where' => 'm.id=pf.friends_friend_id or  m.id=pf.friends_member_id ',
                            'type' => 'left'),
                        1 => array('select' => 'me.*',
                            'from' => array('member_extra' => 'me'),
                            'where' => 'me.id=m.id',
                            'type' => 'left'),
                        2 => array('select' => 'pp.*',
                            'from' => array('profile_portal' => 'pp'),
                            'where' => 'pp.pp_member_id=m.id',
                            'type' => 'left'),
                        3 => array('select' => 'pc.*',
                            'from' => array('pfields_content' => 'pc'),
                            'where' => 'pc.member_id=m.id',
                            'type' => 'left')
                    )
                )
            );
        
        $datas = $this->common->member_load_friends($this->ipsclass->member);
        $datas = (count($datas) < 2) ? null : array_slice($datas, 1, count($datas) - 1);
        if (is_array($datas)) {
            ksort($datas);
        }
        $pages = $this->common->create_customize_paging($stats['count'], $per_page, $start, "", $this->ipsclass->lang['tpl_pages'],"#", TRUE, "all_friend_paging");
        $friends['pages'] = $pages;
        $friends['total_friends'] = count($datas);
        $friends['owned_id'] = $this->ipsclass->member['id'];
        $friends['datas'] = $datas;
        $layout_friends = $this->ipsclass->compiled_templates['skin_regportal']->content_wg_load_all_friends($friends);

        echo $layout_friends;
        exit();
    }

    //-----------------------------------------
    // Created redirect
    //----------------------------------------- 
    function redirect() {

        if ($this->ipsclass->member['id'] == "" || intval($this->ipsclass->member['id']) <= 0) {
            $this->ipsclass->boink_it($this->ipsclass->base_url);
            return;
        }

        if (trim($this->ipsclass->input['method']) == "index") {
            $this->ipsclass->boink_it($this->ipsclass->base_url . '&act=regportal&&CODE=wg');
            return;
        }
        if (trim($this->ipsclass->input['method']) == "profile") {
            $this->ipsclass->boink_it($this->ipsclass->base_url . '&act=regportal&&CODE=wg');
            return;
        }
        if (trim($this->ipsclass->input['method']) == "info") {
            $this->ipsclass->boink_it($this->ipsclass->base_url . "act=reportal&&CODE=pf");
            return;
        }
    }

    //-----------------------------------------
    // Created my_show_page_search
    //----------------------------------------- 
    function my_show_page_search($form_errors=array()) {
        $this->ipsclass->load_template('skin_regportal');

        $this->output = $this->ipsclass->compiled_templates['skin_regportal']->search_friend($temp = '');
    }

    //-----------------------------------------
    // Created my_ajax_edit_profile
    //----------------------------------------- 
    function my_ajax_edit_profile() {
        //$this->ipsclass->input['txt_display_name'] = "";
        if (empty($this->ipsclass->input['txt_display_name'])) {
            echo "display_name_empty";
            exit();
        }
        if (empty($this->ipsclass->input['txtrealname'])) {
            echo "real_name_empty";
            exit();
        }
        if (empty($this->ipsclass->input['txtemail'])) {
            echo "email_empty";
            exit();
        }


        //validate bithday
        //-----------------------------------------
        // Make sure it's a legal date
        //-----------------------------------------

        $_year = $this->ipsclass->input['year'] ? $this->ipsclass->input['year'] : 1999;
        if ($this->ipsclass->input['day'] != '' && $this->ipsclass->input['month'] != '') {
            if (!checkdate($this->ipsclass->input['month'], $this->ipsclass->input['day'], $_year)) {
                echo "birth_error";
                exit();
            }
        }
        $member = array(
            members_display_name => trim($this->ipsclass->input['txt_display_name']),
            email => trim($this->ipsclass->input['txtemail']),
            bday_day => intval(trim($this->ipsclass->input['day'])),
            bday_month => intval(trim($this->ipsclass->input['month'])),
            bday_year => intval(trim($this->ipsclass->input['year']))
        );

        $this->common->save_member('members', $member, ' id = ' . intval($this->ipsclass->member['id']));
        /*
         * 
         * Update table member_extra
         * 
         */
        if ((strlen($this->ipsclass->input['txthobby']) > $this->ipsclass->vars['max_interest_length']) and ($this->ipsclass->vars['max_interest_length'])) {
            echo "hobby_long";
            exit();
        }
        $member_extra = array(
            interests => trim($this->ipsclass->input['txthobby'])
        );
        $this->common->save_member("member_extra", $member_extra, ' id = ' . intval($this->ipsclass->member['id']));

        /*
         * update table pfields_content
         * 
         */
        $real_name = trim($this->ipsclass->input['txtrealname']);

        $keywords = preg_split("/[\s ]+/", $real_name);

        $first_name = count($keywords) >= 1 ? $keywords[0] : "";
        $last_name = "";
        if (sizeof($keywords) >= 2) {
            for ($index = 1; $index < count($keywords); $index++) {
                $last_name .= $keywords[$index];
                if ($index < count($keywords) - 1) {
                    $last_name .= " ";
                }
            }
        }

        $pfields_content = array(
            field_14 => $first_name,
            field_15 => $last_name,
            field_16 => trim($this->ipsclass->input['txtjob'])
        );
        $this->common->save_member("pfields_content", $pfields_content, ' member_id = ' . $this->ipsclass->member['id']);
        //update gender
        $_gender = $this->ipsclass->input['gender'] == 'male' ? 'male' : ( $this->ipsclass->input['gender'] == 'female' ? 'female' : '' );


        //check profile id
        //kiem tra xem trong table profile_portal da co member id hay chua
        $id = $this->check_id('profile_portal', 'pp_member_id', $this->ipsclass->member['id']);
        //neu chua co member thi insert moi
        //nguoc lai: update member do
        if ($id == -1) {
            $this->ipsclass->DB->do_insert('profile_portal', array('pp_gender' => $_gender, 'pp_member_id' => $this->ipsclass->member['id']));
        } else {
            $this->common->save_member("profile_portal", array('pp_gender' => $_gender), ' pp_member_id = ' . $this->ipsclass->member['id']);
        }

        /*
         * update table members_converge
         * 
         */

        $this->ipsclass->DB->do_update('members_converge', array('converge_email' => trim($this->ipsclass->member['email'])), ' converge_id = ' . $this->ipsclass->member['id']);
        //print_r($this->ipsclass->member);
        echo "edit_profile_info_success";
        exit();
    }

    //-----------------------------------------
    // Created change_password
    //----------------------------------------- 
    function change_password() {
        //check validate
        //current pass
        if (empty($this->ipsclass->input['txtpasscurent'])) {
            echo "old_pass_empty";
            exit();
        }

        //new pass
        if (empty($this->ipsclass->input['txtpassnew1'])) {
            echo "new_pass_empty";
            exit();
        }
        //check new pass
        if (empty($this->ipsclass->input['txtpassnew2'])) {
            echo "confirm_pass_empty";
            exit();
        }
        if (trim($this->ipsclass->input['txtpassnew2']) != trim($this->ipsclass->input['txtpassnew1'])) {
            echo "confirm_pass_not_match";
            exit();
        }

        //            //check authentication
        //            Check old password
        //-----------------------------------------
        // Load handler...
        //-----------------------------------------

        require_once( ROOT_PATH . 'sources/handlers/han_login.php' );
        $this->han_login = new han_login();
        $this->han_login->ipsclass = & $this->ipsclass;
        $this->han_login->init();
        $this->han_login->login_authenticate($this->ipsclass->member['name'], $this->ipsclass->input['txtpasscurent']);

        //-----------------------------------------
        // Check return code...
        //-----------------------------------------

        $member_temp = $this->han_login->member;
        if (!$member_temp['id'] || $this->han_login->return_code != 'SUCCESS') {
            echo "old_pass_fail";
            exit();
        }

        //start create password
        $salt = $this->ipsclass->converge->generate_password_salt(5);
        $passhash = $this->ipsclass->converge->generate_compiled_passhash($salt, md5($this->ipsclass->input['txtpassnew1']));
        $converge_array = array(//'converge_email'     => $in_email,
            'converge_joined' => time(),
            'converge_pass_hash' => $passhash,
            'converge_pass_salt' => str_replace('\\', "\\\\", $salt)
        );

        $this->ipsclass->DB->do_update('members_converge', $converge_array, ' converge_id = ' . $this->ipsclass->member['id']);
        //print_r($this->ipsclass->member);
        echo 'change_pass_success';
        exit();
    }

    //-----------------------------------------
    // Created do_avatar
    //----------------------------------------- 
    function do_avatar() {


        //-----------------------------------------
        // Got attachment types?
        //-----------------------------------------

        if (!is_array($this->ipsclass->cache['attachtypes'])) {
            $this->ipsclass->cache['attachtypes'] = array();

            $this->ipsclass->DB->simple_construct(array('select' => 'atype_extension,atype_mimetype,atype_post,atype_photo,atype_img', 'from' => 'attachments_type', 'where' => "atype_photo=1 "));
            $this->ipsclass->DB->simple_exec();

            while ($r = $this->ipsclass->DB->fetch_row()) {
                $this->ipsclass->cache['attachtypes'][$r['atype_extension']] = $r;
            }
        }

        $real_type = "";

        //-----------------------------------------
        // Nawty, Nawty!
        //-----------------------------------------
        // Comment by BabyWolf
        if ($this->ipsclass->input['auth_key'] != $this->class->md5_check && $this->ipsclass->input['act'] != 'Reg') {
            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'del_post'));
        }

        //-----------------------------------------
        // Did we press "remove"?
        //-----------------------------------------

        if (isset($this->ipsclass->input['remove']) AND $this->ipsclass->input['remove']) {
            $this->common->bash_uploaded_avatars($this->ipsclass->member['id']);

            $this->ipsclass->DB->do_update('member_extra', array('avatar_location' => '',
                'avatar_size' => '',
                'avatar_type' => '',
                    ), 'id=' . $this->ipsclass->member['id']);
        }


        //-----------------------------------------
        // Not so fast, big shot.
        //-----------------------------------------

        if ($this->ipsclass->xss_check_url($this->ipsclass->input['url_avatar']) !== TRUE) {
            $this->ipsclass->input['url_avatar'] = '';
        }

        //-----------------------------------------
        // Continue...
        //-----------------------------------------

        if (empty($this->ipsclass->input['url_avatar']) or $this->ipsclass->input['url_avatar'] == "") {
            //-----------------------------------------
            // Lets check for an uploaded photo..
            //-----------------------------------------

            if ($_FILES['updatepic']['name'] != "" and ($_FILES['updatepic']['name'] != "none")) {


                //-----------------------------------------
                // Remove any uploaded avatars..
                //-----------------------------------------

                $this->common->bash_uploaded_avatars($this->ipsclass->member['id']);

                $real_name = 'av-' . $this->ipsclass->member['id'];
                $real_type = 'upload';

                //-----------------------------------------
                // Load the library
                //-----------------------------------------

                require_once( KERNEL_PATH . 'class_upload.php' );
                $upload = new class_upload();
                $upload->set_field_name("updatepic");
                require_once( KERNEL_PATH . 'class_image.php' );
                $this->image = new class_image();

                //-----------------------------------------
                // Set up the variables
                //-----------------------------------------
                //echo $this->ipsclass->vars['my_upload_url'];exit();
                $time = $this->ipsclass->member['joined'];
                $time = date('dmY', $time);
                $strName = $this->ipsclass->member['name'];
                //echo $this->ipsclass->vars['my_upload_url'];exit();
                if (!is_dir($this->ipsclass->vars['my_upload_url'] . "$time"))
                    mkdir($this->ipsclass->vars['my_upload_url'] . "$time", 0777);
                if (!is_dir($this->ipsclass->vars['my_upload_url'] . "$time/$strName"))
                    mkdir($this->ipsclass->vars['my_upload_url'] . "$time/$strName", 0777);
                $upload->out_file_name = 'av-' . $this->ipsclass->member['id'];

                $upload->out_file_dir = $this->ipsclass->vars['my_upload_url'] . "$time/$strName";
                $upload->max_file_size = ($this->ipsclass->vars['avup_size_max'] * 1024); // * 8;  // Allow xtra for compression
                //-----------------------------------------
                // Populate allowed extensions
                //-----------------------------------------

                if (is_array($this->ipsclass->cache['attachtypes']) and count($this->ipsclass->cache['attachtypes'])) {
                    foreach ($this->ipsclass->cache['attachtypes'] as $data) {
                        if ($data['atype_photo']) {
                            $upload->allowed_file_ext[] = $data['atype_extension'];
                        }
                    }
                }

                //-----------------------------------------
                // Upload...
                //-----------------------------------------

                $upload->upload_process();

                //-----------------------------------------
                // Error?
                //-----------------------------------------

                if ($upload->error_no) {
                    //-----------------------------------------
                    // Remove it 'cos there's a problem
                    //-----------------------------------------

                    $this->ipsclass->DB->do_update('member_extra', array('avatar_location' => '', 'avatar_size' => '', 'avatar_type' => ''), 'id=' . $this->ipsclass->member['id']);

                    switch ($upload->error_no) {
                        case 1:
                            // No upload
                            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'upload_failed'));
                            break;
                        case 2:
                            // Invalid file ext
                            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'no_av_type'));
                            break;
                        case 3:
                            // Too big...
                            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'upload_to_big'));
                            break;
                        case 4:
                            // Cannot move uploaded file
                            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'upload_failed'));
                            break;
                        case 5:
                            // Possible XSS attack (image isn't an image)
                            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'upload_failed'));
                            break;
                    }
                }

                //-----------------------------------------
                // Still here?
                //-----------------------------------------

                $real_name = $time . '/' . $strName . '/' . $upload->parsed_file_name;

                if (!$this->ipsclass->vars['disable_ipbsize'] and $upload->file_extension != '.swf') {
                    $this->image->in_type = 'file';
                    $this->image->out_type = 'file';
                    $this->image->in_file_dir = $this->ipsclass->vars['upload_dir'];
                    $this->image->in_file_name = $real_name;
                    $this->image->out_file_name = 'avs-' . $this->ipsclass->member['id'];
                    $this->image->desired_width = $p_width;
                    $this->image->desired_height = $p_height;

                    $return = $this->image->generate_thumbnail();

                    $im['img_width'] = $return['thumb_width'];
                    $im['img_height'] = $return['thumb_height'];

                    //-----------------------------------------
                    // Do we have an attachment?
                    //-----------------------------------------

                    if (isset($return['thumb_location']) AND strstr($return['thumb_location'], 'avs-')) {
                        //-----------------------------------------
                        // Kill old and rename new...
                        //-----------------------------------------

                        @unlink($this->ipsclass->vars['my_upload_url'] . $real_name);

                        $real_name = 'av-' . $this->ipsclass->member['id'] . '.' . $this->image->file_extension;

                        @rename($this->ipsclass->vars['my_upload_url'] . $return['thumb_location'], $this->ipsclass->vars['upload_dir'] . "/" . $real_name);
                        @chmod($this->ipsclass->vars['my_upload_url'] . $real_name, 0777);
                    }
                } else {
                    $w = intval($this->ipsclass->input['man_width']) ? intval($this->ipsclass->input['man_width']) : $p_width;
                    $h = intval($this->ipsclass->input['man_height']) ? intval($this->ipsclass->input['man_height']) : $p_height;
                    $im['img_width'] = $w > $p_width ? $p_width : $w;
                    $im['img_height'] = $h > $p_height ? $p_height : $h;
                }

                //-----------------------------------------
                // Check the file size (after compression)
                //-----------------------------------------

                if (@filesize($this->ipsclass->vars['my_upload_url'] . $real_name) > ($this->ipsclass->vars['avup_size_max'] * 1024)) {
                    @unlink($this->ipsclass->vars['my_upload_url'] . $real_name);

                    $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'upload_to_big'));
                }

                //-----------------------------------------
                // Set the "real" avatar..
                //-----------------------------------------

                $real_choice = $real_name;
                $real_dims = $im['img_width'] . 'x' . $im['img_height'];
            } else {
                //-----------------------------------------
                // URL field and upload field left blank.
                //-----------------------------------------

                $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'no_avatar_selected'));
            }
        } else {
            //-----------------------------------------
            // It's an entered URL 'ting man
            //-----------------------------------------

            $this->ipsclass->input['url_avatar'] = trim($this->ipsclass->input['url_avatar']);

            if (empty($this->ipsclass->vars['allow_dynamic_img'])) {
                if (preg_match("/[?&;]/", $this->ipsclass->input['url_avatar'])) {
                    $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'avatar_invalid_url'));
                }
            }

            //-----------------------------------------
            // Check extension
            //-----------------------------------------

            $ext = explode(",", $this->ipsclass->vars['avatar_ext']);
            $checked = 0;
            $av_ext = preg_replace("/^.*\.(\S+)$/", "\\1", $this->ipsclass->input['url_avatar']);

            foreach ($ext as $v) {
                if (strtolower($v) == strtolower($av_ext)) {
                    if (( $v == 'swf' ) AND ($this->ipsclass->vars['allow_flash'] != 1)) {
                        $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'no_flash_av'));
                    }

                    $checked = 1;
                }
            }

            if ($checked != 1) {
                $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'avatar_invalid_ext'));
            }

            //-----------------------------------------
            // Check image size...
            //-----------------------------------------

            $im = array();

            if (!$this->ipsclass->vars['disable_ipbsize']) {
                if (!$img_size = @GetImageSize($this->ipsclass->input['url_avatar'])) {
                    $img_size[0] = $p_width;
                    $img_size[1] = $p_height;
                }

                $im = $this->ipsclass->scale_image(array(
                    'max_width' => $p_width,
                    'max_height' => $p_height,
                    'cur_width' => $img_size[0],
                    'cur_height' => $img_size[1]
                        )
                );
            } else {
                $w = intval($this->ipsclass->input['man_width']) ? intval($this->ipsclass->input['man_width']) : $p_width;
                $h = intval($this->ipsclass->input['man_height']) ? intval($this->ipsclass->input['man_height']) : $p_height;
                $im['img_width'] = $w > $p_width ? $p_width : $w;
                $im['img_height'] = $h > $p_height ? $p_height : $h;
            }

            //-----------------------------------------
            // Remove any uploaded images..
            //-----------------------------------------

            $this->common->bash_uploaded_avatars($this->ipsclass->member['id']);

            $real_choice = $this->ipsclass->input['url_avatar'];
            $real_dims = $im['img_width'] . 'x' . $im['img_height'];
            $real_type = 'url';
        }

        //-----------------------------------------
        // Update the DB
        //-----------------------------------------

        $this->ipsclass->DB->do_update('member_extra', array('avatar_location' => $real_choice, 'avatar_size' => $real_dims, 'avatar_type' => $real_type), 'id=' . $this->ipsclass->member['id']);
        $this->ipsclass->boink_it($this->ipsclass->base_url . 'act=regportal&&CODE=pf');
    }

    //-----------------------------------------
    // Created delete_pic
    //-----------------------------------------
    function delete_pic() {
        //check member id
        if (empty($this->ipsclass->member['id'])) {
            echo "member_fail";
            exit();
        }
        //remove avatar
        //$this->bash_uploaded_avatars(intval($this->ipsclass->member['id']));
        $this->delete_avatar($this->ipsclass->member['avatar_location']);

        //update data
        $this->common->bash_uploaded_avatars($this->ipsclass->member['id']);

        $this->ipsclass->DB->do_update('member_extra', array('avatar_location' => '',
            'avatar_size' => '',
            'avatar_type' => '',
                ), 'id=' . $this->ipsclass->member['id']);
        echo "delete_pic_success";
        exit();
    }
/*
         * author@chung nguyen huu
         * Date: 2011/09/22
         */
    function delete_avatar($avatar_location){
            if(@file_exists($this->ipsclass->vars['my_upload_url'].$avatar_location)){
                @unlink($this->ipsclass->vars['my_upload_url'].$avatar_location);
            }
        }

    //-----------------------------------------
    // Created owned_comment
    //-----------------------------------------
    function owned_comment() {
        $comment_approved = 1;
        $comment = "";
        //echo $this->ipsclass->input['txtmycomment'];exit();
        if (empty($this->ipsclass->input['txtmycomment'])) {
            echo "comment_empty";
            exit();
        }
        $per_page = intval($this->ipsclass->vars['social_per_page_setting']) <=0 ? 25 :  $this->ipsclass->vars['social_per_page_setting'];
        $start = intval($this->ipsclass->input['st']) >= 0 ? intval($this->ipsclass->input['st']) : 0;
        //-----------------------------------------
        // Load XML class
        //-----------------------------------------

        require_once( KERNEL_PATH . 'class_ajax.php' );
        $class_ajax = new class_ajax();
        $class_ajax->ipsclass = & $this->ipsclass;
        $class_ajax->class_init();
        /*
         * su ly du lieu truoc khi dua vao database
         * 
         */
        $comment = $class_ajax->convert_unicode($this->ipsclass->input['txtmycomment']);
        $comment = $class_ajax->convert_html_entities($this->ipsclass->input['txtmycomment']);
        $for_id = intval($this->ipsclass->input['own_id']);
        //$comment = $this->ipsclass->parse_clean_value( $this->ipsclass->input['txtmycomment'] );
        $comment = $class_ajax->ipsclass->txt_mbsubstr($comment, 0, 400);
        $comment = preg_replace("#(\r\n|\r|\n|<br />|<br>){1,}#s", "\n", $comment);
        //-----------------------------------------
        // Bad words
        //-----------------------------------------
        //$comment = trim( $this->parser->bad_words( $comment ) );
        // Added by BabyWolf to parse comment with emoticons

        $this->parser->parse_smilies = 1;
        $this->parser->parse_html = 0;
        $this->parser->parse_nl2br = 1;
        $this->parser->parse_bbcode = 0;
        $this->parser->bypass_badwords = intval($this->ipsclass->member['g_bypass_badwords']);
        $this->ipsclass->DB->do_insert('profile_comments', array('comment_for_member_id' => $for_id,
            'comment_by_member_id' => $this->ipsclass->member['id'],
            'comment_date' => time(),
            'comment_ip_address' => $this->ipsclass->ip_address,
            'comment_approved' => $comment_approved,
            'comment_content' => $this->ipsclass->my_nl2br($comment)));
        //lay ra id cua comment vua insert
        //kiem tra va thong bao den client
        //-----------------------------------------
        // Regenerate comments... by tuanhnm
        //-----------------------------------------
        $sql_extra = '';
        $comments[] = array();
        $member = $this->common->format_member($this->ipsclass->member['id']);
        if ($for_id != $this->ipsclass->member['id']) {
            $datas = $this->common->member_load_comment($member, $per_page, $start, $this->ipsclass->member['id'], $sql_extra);
        } else {
            $datas = $this->common->member_load_comment($member, $per_page, $start, $sql_extra);
        }
        $stats = $this->ipsclass->DB->simple_exec_query(array('select' => 'count(pc.comment_id) as count',
            'from' => 'profile_comments pc',
            'where' => ' pc.comment_by_member_id = ' . $member['id']
                )
        );
        
        /*
         * Paging
         */
        $pages = $this->common->create_customize_paging($stats['count'], $per_page, $start, "", $this->ipsclass->lang['tpl_pages'],'#');
        $comments['pages'] = $pages;
        $comments['total_comments'] = count($datas);
        $comments['datas'] = $datas;
        $layout_comment = $this->ipsclass->compiled_templates['skin_regportal']->content_wg_comment_02($comments);
        //		
        echo "own_comment_success[$$$$$]" . $layout_comment;
        unset($comment);
        unset($layout_comment);
        exit();
    }

    //-----------------------------------------
    // Create load_comments
    //-----------------------------------------
    function load_comments() {
        //load skin
        $this->ipsclass->load_template('skin_regportal');

        //-----------------------------------------
        // Check viewing permissions, etc
        //-----------------------------------------

        if (!$this->ipsclass->member['id']) {
            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'no_guests'));
        }
        //var_dump($this->ipsclass->vars['cookie_id']);exit();

        $_member_ids = array();

        $comments[] = array();
        $sql_extra = '';
        $member_id = intval($this->ipsclass->member['id']);
        $per_page = intval($this->ipsclass->vars['social_per_page_setting']) <=0 ? 25 :  $this->ipsclass->vars['social_per_page_setting'];
        $start = intval($this->ipsclass->input['st']) >= 0 ? intval($this->ipsclass->input['st']) : 0;
        $member = $this->common->format_member($member_id);
        /*
         * Author: chungnguyenhuu@godfather.typhoon.tycoon
         * Update : 2011/09/14
         * Load member from another function
         */
        $datas = $this->common->member_load_comment($member, $sql_extra, $per_page, $start);
       
        //count total
        $stats = $this->ipsclass->DB->simple_exec_query(array('select' => 'count(pc.comment_id) as count',
            'from' => 'profile_comments pc',
            'where' => ' pc.comment_by_member_id = ' . $member['id']
                )
        );

        /*
         * Paging
         */
        $pages = $this->common->create_customize_paging($stats['count'], $per_page, $start, "", $this->ipsclass->lang['tpl_pages'],'#');
        $comments['pages'] = $pages;
        $comments['total_comments'] = count($datas);
        $comments['datas'] = $datas;
        $layout_comment = $this->ipsclass->compiled_templates['skin_regportal']->content_wg_comment_02($comments);
        echo $layout_comment;
        exit();
    }

    //-----------------------------------------
    // Create delete_owned_comment
    //-----------------------------------------
    function delete_owned_comment() {
        $comment_id = "";
        $comment_for_member_id = "";
        $comment_by_member_id = "";
        $per_page = intval($this->ipsclass->vars['social_per_page_setting']) <=0 ? 25 :  $this->ipsclass->vars['social_per_page_setting'];
        $start = intval($this->ipsclass->input['st']) >= 0 ? intval($this->ipsclass->input['st']) : 0;
        //lay id tu client
        $id_str = $this->ipsclass->input['id'];

        $ids = explode("_", $id_str);

        if (count($ids) != 3) {
            echo "own_delete_param_invalid";
            exit();
        }

        $comment_id = intval($ids[0]);
        $comment_by_member_id = intval($ids[1]);
        $comment_for_member_id = intval($ids[2]);
        if($this->ipsclass->member['g_is_supmod']){
            $this->ipsclass->DB->build_and_exec_query(array('delete' => 'profile_comments',
                                                            'where' => 'comment_id=' . $comment_id
                                                            )
                                                        );
            echo "own_delete_comment_success[$$$$$]";
            exit();
        }else 
        if ($comment_by_member_id != $this->ipsclass->member['id'] && $comment_for_member_id != $this->ipsclass->member['id']) {
            echo "own_delete_access_deny";
            exit();
        }
        if ($comment_by_member_id == $this->ipsclass->member['id'] || $comment_for_member_id == $this->ipsclass->member['id']/* ($comment_for_member_id == $this->ipsclass->member['id'] && $comment_by_member_id == $this->ipsclass->member['id']) */) {
            $this->ipsclass->DB->build_and_exec_query(array('delete' => 'profile_comments',
                'where' => 'comment_id=' . $comment_id));
        }
        echo "own_delete_comment_success[$$$$$]";
        exit();
    }

    //-----------------------------------------
    // Create find_friends_by_name
    //-----------------------------------------
    function find_friends_by_name() {
        $this->ipsclass->load_template('skin_regportal');
        $this->ipsclass->load_language('lang_profile');
        $this->ipsclass->load_template('skin_profile');
        $name = $this->ipsclass->input['txtsearch'];
        
        require (KERNEL_PATH . "class_ajax.php");
        $xml_convert = new class_ajax();
        $xml_convert->ipsclass = & $this->ipsclass;
        $this->ipsclass->input['key'] = $xml_convert->convert_and_make_safe($this->ipsclass->input['key']);
        $key = $this->ipsclass->input['key'];
        $per_page = intval($this->ipsclass->vars['social_per_page_setting']) <=0 ? 25 :  $this->ipsclass->vars['social_per_page_setting'];
        $start = intval($this->ipsclass->input['st']) >= 0 ? intval($this->ipsclass->input['st']) : 0;
        //echo $start;
        if (!empty($key)) {
            $name = $key;
        }
        //rss
        $name = htmlspecialchars($name);
        require( ROOT_PATH . 'sources/action_public/search.php' );
        $search = new search;
        $search->ipsclass = & $this->ipsclass;
        $name = $search->filter_keywords($name, 0);
        $main_clause = "";
        $sql = "";
        $name = strtolower(trim($name));
        $friends[] = array();
        $friends_friends = array();
        $stats = array();
        $has_member = -1;
        if (!empty($name)) {
            
            $names = explode(" ", $name);
            //check username
            $has_member = $this->count("members", "name", "name = '$name'" );
            if($has_member == 1){
                $sql_like = "m.name = '$name'";
            }else{
                $names = explode(" ", $name);
                if (count($names) == 1) {
                    $sql_like = "cf.field_14 like LOWER('%{$name}%') or cf.field_15 like LOWER('%{$name}%')";
                } else {
                    $temp = implode(" ", array_slice($names, 1));
                    $main_clause = "( cf.field_14 = LOWER('" . $names[0] . "') and cf.field_15 = LOWER('" . $temp . "') ) and ";
                    $tem1 = array();
                    $tem2 = array();
                    for ($index = 0; $index < count($names); $index++) {
                        $tem1[] = "cf.field_14 like LOWER('%" . $names[$index] . "%')";
                        $tem2[] = "cf.field_15 like LOWER('%" . $names[$index] . "%')";
                    }
                    $str1 = implode(" or ", $tem1);
                    $str2 = implode(" or ", $tem2);
                    $sql_like = $str1 . " or " . $str2;
                }
                $sql_like = $main_clause . " " . $sql_like;
            }
            $key = $name;
            $this->ipsclass->DB->flush_query();
            $this->ipsclass->DB->build_query(array('select' => 'cf.*',
                'from' => array('pfields_content' => 'cf'),
                'where' => $sql_like,
                'limit' => array($start, $per_page),
                'add_join' => array(0 => array(
                        'select' => 'm.*, m.name as username',
                        'from' => array('members' => 'm'),
                        'where' => 'm.id = cf.member_id',
                        'type' => 'left'
                    ),
                    1 => array('select' => 'pp.*',
                        'from' => array('profile_portal' => 'pp'),
                        'where' => 'pp.pp_member_id=m.id',
                        'type' => 'left'),
                    2 => array('select' => 'me.*',
                        'from' => array('member_extra' => 'me'),
                        'where' => 'me.id=m.id',
                        'type' => 'left')
                )
                    )
            );
            $this->ipsclass->DB->exec_query();
            $friends_friends = array();
            while ($row = $this->ipsclass->DB->fetch_row()) {
                $datas[] = $this->ipsclass->member_set_information($row);
            }
            //var_dump($datas);exit();
            //count total
            if($has_member == 1){
                $stats = $this->ipsclass->DB->simple_exec_query(array('select' => 'count(m.id) as count',
                    'from' => 'members m',
                    'where' => $sql_like
                        )
                );
            }else{
                $stats = $this->ipsclass->DB->simple_exec_query(array('select' => 'count(cf.member_id) as count',
                    'from' => 'pfields_content cf',
                    'where' => $sql_like
                        )
                );
            }
            
            /*
             * Paging
             */
            $pages = $this->common->create_customize_paging($stats['count'], $per_page, $start, "", $this->ipsclass->lang['tpl_pages'],"#&" . $key, TRUE, 'own_search_paging');
        }
        //echo $pages . "aaa";
        //exit();
        $friends['pages'] = $pages;
        $friends['total_friends'] = count($datas);
        $friends['owned_id'] = $this->ipsclass->member['id'];
        $friends['datas'] = $datas;
        $layout_friends = $this->ipsclass->compiled_templates['skin_regportal']->content_wg_search_friends($friends);
        echo $layout_friends;
        exit();
    }

    //-----------------------------------------
    // Create search_suggest
    //-----------------------------------------
    function search_suggest() {
        $name = $this->common->replace_unicode($this->ipsclass->input['name']);
        $name = htmlspecialchars($name);
        $name = htmlentities(trim($name));
        echo $name;
        exit();
    }

    //-----------------------------------------
    // Create load_all_member
    //-----------------------------------------
    function load_all_member() {
        //$member_id = intval($this->ipsclass->member['id']);
        //find member by username
        $names = array();
        $this->ipsclass->DB->flush_query();
        $this->ipsclass->DB->build_query(array('select' => 'm.*',
            'from' => 'members m ',
            'where' => ' 1 = 1; ')
        );
        $this->ipsclass->DB->exec_query();
        while ($row = $this->ipsclass->DB->fetch_row()) {
            //$temp = trim($row['name']);
            if (!empty($row['name'])){
                $names[] = $row['name'];
            }
                
        }
        
        $this->ipsclass->DB->flush_query();
        $this->ipsclass->DB->build_query(array('select' => 'pc.*',
            'from' => 'pfields_content pc ',
            'where' => ' 1 = 1; ')
        );
        $this->ipsclass->DB->exec_query();
        while ($row = $this->ipsclass->DB->fetch_row()) {
            $temp = trim($row['field_14'] . " " . $row['field_15']);
            if (!empty($temp))
                $names[] = $temp;
        }
        //var_dump($names);
        echo implode("[$$$$$]", $names);
        exit();
    }

    //-----------------------------------------
    // Create add_friend
    //-----------------------------------------
    function add_friend() {

        $member_id = $this->ipsclass->input['member_id'];
        $friend_id = $this->ipsclass->input['friends_id'];
        $text = strtolower(trim($this->ipsclass->input['text']));
        switch ($text) {
            case "hủy":
                if ($friend_id == $this->ipsclass->member['id']) {
                    $this->ipsclass->DB->build_and_exec_query(array(
                                                            'delete' => 'profile_friends',
                                                            'where' => ' friends_member_id = ' . intval($friend_id) . " and friends_friend_id = " . intval($member_id) . " and friends_approved = 1 "
                                                                )
                                                        );
                
                    echo 'owned_removed_success';
                    exit();
                }
            
                
                break;
            case "wait":
                break;
            case "mời":
                $id = $this->common->check_friend($friend_id, $member_id);
                if (intval($id) <= 0) {
                    $this->ipsclass->DB->do_insert('profile_friends', array('friends_member_id' => $friend_id,
                        'friends_friend_id' => $member_id,
                        'friends_approved' => 0,
                        'friends_added' => time()));
                    $friend = $this->ipsclass->DB->get_insert_id();
                    echo "own_add_friend_success";
                    exit();
                }
                break;
            case "invite":
                $id = $this->common->check_friend($friend_id, $member_id);
                if (intval($id) <= 0) {
                    $this->ipsclass->DB->do_insert('profile_friends', array('friends_member_id' => $friend_id,
                        'friends_friend_id' => $member_id,
                        'friends_approved' => 0,
                        'friends_added' => time()));
                    $friend = $this->ipsclass->DB->get_insert_id();
                    echo "own_add_friend_success";
                    exit();
                }
                break;
            default :
                break;
        }

        //echo "own_add_friend_success";
        //exit();
    }

    //-----------------------------------------
    // Create is_friend
    //-----------------------------------------
    function is_friend($friend = FALSE) {
        $member_id = $this->ipsclass->input['member_id'];
        //var_dump($this->ipsclass->input);
        $friend_id = $this->ipsclass->input['friends_id'];
        //$friend_id = $this->ipsclass->member['id'];
        $index_item = $this->ipsclass->input['index_item'];
        $this->ipsclass->DB->simple_construct(array('select' => 'pf.friends_approved as friends_approved',
            'from' => 'profile_friends pf',
            'where' => 'pf.friends_member_id' . ' = ' . $friend_id . ' and pf.friends_friend_id = ' . $member_id,
            'limit' => array(0, 1)
                )
        );
        $this->ipsclass->DB->simple_exec();
        error_reporting(E_ALL);
        $result = $this->ipsclass->DB->fetch_row();
        if (!empty($result) && $result['friends_approved'] != "") {
            echo $result['friends_approved'] . "_" . $index_item . "_" . $member_id . "_" . $friend_id;
            exit();
        }
        echo -1 . "_" . $index_item . "_" . $member_id . "_" . $friend_id;
        exit();
    }

    //-----------------------------------------
    // Create personal_function_load_member
    //-----------------------------------------
    function personal_function_load_member($member_id=0) {

        $query = '';

        //-----------------------------------------
        // What do we have?
        //-----------------------------------------

        if (is_array($member_id)) {
            $query = 'm.id IN (' . implode(',', $member_id) . ')';
        } else {
            $query = 'm.id=' . intval($member_id);
        }

        //-----------------------------------------
        // Load member
        //-----------------------------------------

        $this->ipsclass->DB->build_query(array('select' => 'm.*',
            'from' => array('members' => 'm'),
            'where' => $query,
            'add_join' => array(0 => array('select' => 'me.*',
                    'from' => array('member_extra' => 'me'),
                    'where' => 'me.id=m.id',
                    'type' => 'left'),
                1 => array('select' => 'pp.*',
                    'from' => array('profile_portal' => 'pp'),
                    'where' => 'pp.pp_member_id=m.id',
                    'type' => 'left'),
                2 => array('select' => 'g.*',
                    'from' => array('groups' => 'g'),
                    'where' => 'g.g_id=m.mgroup',
                    'type' => 'left'),
                3 => array('select' => 's.location_1_id, s.location_2_id, s.location_1_type, s.location_2_type, s.running_time, s.location as sesslocation',
                    'from' => array('sessions' => 's'),
                    'where' => "s.member_id=m.id",
                    'type' => 'left'),
                4 => array('select' => 'pc.*',
                    'from' => array('pfields_content' => 'pc'),
                    'where' => 'pc.member_id=m.id',
                    'type' => 'left'))));
        $this->ipsclass->DB->exec_query();

        if (is_array($member_id)) {
            while ($row = $this->ipsclass->DB->fetch_row()) {
                $member[$row['id']] = $row;
            }
        } else {
            $member = $this->ipsclass->DB->fetch_row();
            
            $member['pp_setting_count_visitors'] = ( $member['pp_setting_count_visitors'] != 0 ) ? $member['pp_setting_count_visitors'] : 5;
            $member['pp_setting_count_comments'] = ( $member['pp_setting_count_comments'] != 0) ? $member['pp_setting_count_comments'] : 5;
            $member['pp_setting_count_friends'] = ( $member['pp_setting_count_friends'] != 0 ) ? $member['pp_setting_count_friends'] : 5;
            
            /*
             * 
             */
            $member['joined'] = date  ('Y m, d', $member['joined']);
            $member['last_visit'] = date  ('Y m, d', $member['last_visit']);
            //$now =  date("Y m, d, g:i a");
            $time = time();
            $member['now'] = date("Y m, d") ." - ".$this->ipsclass->get_date($time, 'SHORT');
            $member['total_topic'] = $this->count("topics", "tid", " starter_id = " . $member['id']);
            //echo (time() - $member['joined'])/365/12/30/24/60/60;exit();
            
            $member['avg_post'] = substr((time() - $member['joined'])/365/12/30/24/60/60, 0, 4);
            //field_4 : level
            //field_1: HP
            //field_2: MP
            //field_3: EXP
            //field_5: Danh vong
        }
        
        
        //-----------------------------------------
        // Add it to the cached list
        //-----------------------------------------
        
        return $member;
    }

    //-----------------------------------------
    // personal_portal_set_information
    //-----------------------------------------
    function personal_portal_set_information($member, $noids=0, $use_parsed=1) {
        return $this->ipsclass->member_set_information($member, $noids, $use_parsed);
    }

    //-----------------------------------------
    // member_load_friends
    //-----------------------------------------
    function member_load_friends($member, $clause = "", $per_page = "", $start = "") {


        //start paging
        $per_page = intval($this->ipsclass->vars['social_per_page_setting']) <=0 ? 25 :  $this->ipsclass->vars['social_per_page_setting'];
        $start = intval($this->ipsclass->input['st']) >= 0 ? intval($this->ipsclass->input['st']) : 0;
        /*
         * Check clause (search mode)
         * 
         */
        $friends[] = array();

        $query = ' ( pf.friends_member_id = ' . intval($member['id']) . ' or pf.friends_friend_id = ' . intval($member['id']) . ')  AND pf.friends_approved = 1 AND  m.id <> ' . intval($member['id']) . ' group by concat( m.id )';

        $this->ipsclass->DB->flush_query();
        $this->ipsclass->DB->build_query(array('select' => ' pf.*',
            'from' => array('profile_friends' => 'pf'),
            'where' => $query,
            'limit' => array($start, $per_page),
            'add_join' => array(0 => array('select' => 'm.*',
                    'from' => array('members' => 'm'),
                    'where' => 'm.id=pf.friends_friend_id or  m.id=pf.friends_member_id ',
                    'type' => 'left'),
                1 => array('select' => 'me.*',
                    'from' => array('member_extra' => 'me'),
                    'where' => 'me.id=m.id',
                    'type' => 'left'),
                2 => array('select' => 'pp.*',
                    'from' => array('profile_portal' => 'pp'),
                    'where' => 'pp.pp_member_id=m.id',
                    'type' => 'left'),
                3 => array('select' => 'pc.*',
                    'from' => array('pfields_content' => 'pc'),
                    'where' => 'pc.member_id=m.id',
                    'type' => 'left')
            )
                )
        );
        $this->ipsclass->DB->exec_query();

        while ($row = $this->ipsclass->DB->fetch_row()) {
            $friends[] = $this->ipsclass->member_set_information($row);
        }

        unset($member);

        return $friends;
    }

    //-----------------------------------------
    // member_load_comment
    //-----------------------------------------
    function member_load_comment($member, $member_id="", $sql_extra = null, $per_page= "", $start = "") {
        //echo $per_page;exit();
        //start paging
        $per_page = intval($this->ipsclass->vars['social_per_page_setting']) <=0 ? 25 :  $this->ipsclass->vars['social_per_page_setting'];
        $start = intval($this->ipsclass->input['st']) >= 0 ? intval($this->ipsclass->input['st']) : 0;

        //-----------------------------------------
        // Regenerate comments... by tuanhnm
        //-----------------------------------------

        $this->ipsclass->DB->flush_query();

        $this->ipsclass->DB->build_query(array('select' => 'pc.*',
            'from' => array('profile_comments' => 'pc'),
            'where' => 'pc.comment_by_member_id=' . intval($member['id']) . " or(pc.comment_for_member_id = " . intval($member['id']) . " and pc.comment_by_member_id = " . intval($member_id) . " ) " . $sql_extra,
            'limit' => array($start, $per_page),
            'order' => 'pc.comment_date DESC',
            'add_join' => array(0 => array('select' => 'm.name, m.members_display_name, m.login_anonymous',
                    'from' => array('members' => 'm'),
                    'where' => 'm.id=pc.comment_by_member_id',
                    'type' => 'left'),
                1 => array('select' => 'pp.*',
                    'from' => array('profile_portal' => 'pp'),
                    'where' => 'pp.pp_member_id=m.id',
                    'type' => 'left'),
                2 => array('select' => 'me.*',
                    'from' => array('member_extra' => 'me'),
                    'where' => 'me.id=pc.comment_by_member_id',
                    'type' => 'left'))));


        $this->ipsclass->DB->exec_query();

        while ($row = $this->ipsclass->DB->fetch_row()) {
            $row['_comment_date'] = $this->ipsclass->get_date($row['comment_date'], 'SHORT');
            $row['_avatar'] = $this->ipsclass->get_avatar($row['avatar_location'], $this->ipsclass->member['view_avs'], $row['avatar_size'], $row['avatar_type']);
            $row['_last_active'] = $this->ipsclass->get_date($row['last_activity'], 'SHORT');
            // Added by BabyWolf
            $row['name'] = strtolower($row['name']);

            if ($row['login_anonymous']{0} == '1') {
                // Member last logged in anonymous

                if ($this->ipsclass->member['mgroup'] != $this->ipsclass->vars['admin_group'] OR $this->ipsclass->vars['disable_admin_anon']) {
                    $row['_last_active'] = $this->ipsclass->lang['private'];
                }
            }

            $row['comment_content'] = $this->ipsclass->txt_wordwrap($row['comment_content'], '19', ' ');

            $row = $this->common->personal_portal_set_information($row, 0, 0);

            $comments[] = $row;
        }
        return $comments;
    }

    //-----------------------------------------
    // count
    //-----------------------------------------
    function count($table_name, $column_count_name, $clause = null) {
        if (!empty($clause)) {
            $clause .= " and ";
        }
        $this->ipsclass->DB->flush_query();
        $this->ipsclass->DB->build_query(array('select' => 'count(' . $column_count_name . ') as total',
            'from' => $table_name,
            'where' => $clause . ' 1 = 1; ')
        );
        $this->ipsclass->DB->exec_query();
        $row = $this->ipsclass->DB->fetch_row();
        return $row['total'];
        //return 0;
    }
     /*
         * Chung nguyen huu
         * Save data to database
         * 
         */
    function save_member($table_name,$member, $where){
        $this->ipsclass->DB->do_update($table_name, $member, $where);
    }
    function check_id($table_name, $id_column_name, $id, $select_column = ""){
        $str_select = "";
        if(!empty ($select_column) || $select_column != ""){
            $str_select = $select_column;
        }else{
            $str_select = $id_column_name;
        }

        $this->ipsclass->DB->simple_construct(array('select'=> $str_select,
                                                    'from'		=> $table_name,
                                                    'where'             => $id_column_name . ' = ' . $id,
                                                    'order'		=> $id_column_name,
                                                    'limit'		=> array(0,1)
                                                    )
                                            );

        $this->ipsclass->DB->simple_exec();
        error_reporting(E_ALL);
        while($result = $this->ipsclass->DB->fetch_row()){
            return $result[$id_column_name];
        }
        return -1;


    }
    /*
     * reject friend
     * 
     */
    function reject_friend(){
        $member_id = $this->ipsclass->input['member_id'];
        $friend_id = $this->ipsclass->input['friend_id'];
        //echo $member_id . $friend_id;exit();
        if (empty($member_id)) {
            echo "author_fail";
            exit();
        }
        if (empty($friend_id)) {
            echo "not_friend";
            exit();
        }
        $friends_member = array(
            'friends_approved' => 1
        );
        if ($friend_id == $this->ipsclass->member['id']) {
            $this->ipsclass->DB->build_and_exec_query(array(
                                                        'delete' => 'profile_friends',
                                                        'where' => ' friends_member_id = ' . intval($friend_id) . " and friends_friend_id = " . intval($member_id) . " and friends_approved = 0 "
                                                            )
                                                    );
        }

        echo 'owned_rejected_success';
        exit();
    }
    /*
     * remove friend
     * 
     */
    function remove_friend(){
            $member_id = $this->ipsclass->input['member_id'];
            $friend_id = $this->ipsclass->input['friend_id'];
            if (empty($member_id)) {
                echo "author_fail";
                exit();
            }
            if (empty($friend_id)) {
                echo "not_friend";
                exit();
            }
            
            if ($friend_id == $this->ipsclass->member['id']) {
                $this->ipsclass->DB->build_and_exec_query(array(
                                                            'delete' => 'profile_friends',
                                                            'where' => ' friends_member_id = ' . intval($friend_id) . " and friends_friend_id = " . intval($member_id) . " and friends_approved = 1 "
                                                                )
                                                        );
            }
            
            echo 'owned_removed_success';
            exit();
        }
    function init(){
        $this->ipsclass->load_language('lang_regportal');
        $this->ipsclass->load_language('lang_genaral');
        $this->ipsclass->load_template('skin_regportal');
    }
}
?>


